【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进行在线评测

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值