题解 | #乘积为正数的最长连续子数组#

乘积为正数的最长连续子数组

http://www.nowcoder.com/practice/0112b9b5a09048d89309f55ea666db91

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for(int i=0;i<n;i++)
            arr[i] = sc.nextInt();
        int[] pos = new int[n+1]; //以arr[i-1]结尾的乘积为正数的最长长度
        int[] neg = new int[n+1]; //以arr[i-1]结尾的乘积为负数的最长长度
        int res = 0;
        for(int i=1;i<=n;i++){
            if(arr[i-1] > 0){    //如果当前数为正数
                pos[i] = pos[i-1] + 1; //前一个正数+1
                neg[i] = neg[i-1]==0?0:neg[i-1]+1; //前一个负长度为0,仍为0,否则+1
            }else if(arr[i-1] < 0){
                pos[i] = neg[i-1]==0?0:neg[i-1]+1;//前一个负长度为0,仍为0,否则+1
                neg[i] = pos[i-1]+1;//前一个正数长度+1
            }else{
                pos[i] = 0;
                neg[i] = 0;
            }
            res = Math.max(res,pos[i]);
        }
        System.out.println(res);
    }
}
全部评论

相关推荐

09-03 14:50
长春大学 Java
牛客407945238号:这环境…怎么看都像是低配版的电诈园区
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务