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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int i = in.nextInt();
        long []a = new long[i];
        while (in.hasNextLong() && i > 0) { // 注意 while 处理多个 case
            a[a.length - i--] = in.nextLong();
        }
        System.out.print(dp(a));
    }

    public static long dp(long a[]) {
        long []pos = new long[a.length];
        long []neg = new long[a.length];
        if( a[0] > 0){
            pos[0] = 1;
            neg[0] = 0;
        }else{
            pos[0] = 0;
            neg[0] = 1;
        }

        for (int i =  1; i < a.length ; i ++) {
            if(a[i] > 0){
                pos[i] = pos[i-1] + 1;
                neg[i] = neg[i-1] > 0 ? neg[i-1] + 1 : 0;
            }else if(a[i] < 0){
                pos[i] = neg[i-1] > 0 ? neg[i-1] + 1 : 0;
                neg[i] = pos[i-1] + 1; 
            }else{
                pos[i] = 0;
                neg[i] = 0;
            }
        }

        long res = Integer.MIN_VALUE;
        for (int i = 0 ; i < pos.length ; i ++) {
            if(pos[i] > res)
                res = pos[i];
        }
        return res;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务