【LintCode题解|交错子数列】

【题目描述】
给定一个数列,求一个最长的连续子数列,该数列的所有第i个数都有a[i]>=0、a[i+1]<=0、a[i+2]>=0或a[i]<=0、a[i+1]>=0、a[i+2]<=0,即非负数和非正数交替出现,返回最长的长度。

【题目样例 】
Example 1:
Input: a = [2,3,-3,4,-2,0,2,-1]
Output: 5
Explanation:
[3, -3, 4, -2, 0] and [0, 2, -1] meet the requirements, where
in the former has a length of 5 and the latter has a length of 3.

Example 2:
Input: a = [0,0,0,1]
Output: 4
Explanation:a[0]<=0, a[1]>=0, a[2]<=0, a[3]>=0, the entire sequence
meets the requirements.

【题目解析(Java)】
贪心的思想,因为要非正数、非负数交替,positive 表示当前的数之前以正数结尾的最长长度,negative 表示当前的数之前以负数结尾的最长长度。
则有 a[i] >= 0 positive = negative + 1
a[i] <= 0 negative = positive + 1
然后答案就是原本的最长长度,与 positive 和 negative进行比较取最大。具体解析见图片哦~
在这里插入图片描述

点击Lintcode进行在线评测

发布了438 篇原创文章 · 获赞 64 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/JiuZhang_ninechapter/article/details/103787055