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

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

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int len = sc.nextInt();
        int[] nums = new int[len];
        for(int i = 0; i < len; i++) {
            nums[i] = sc.nextInt();
        }
        //到下标i为止的乘积为正数的最长子数组长度
        int[] positive = new int[len];
        //到下标i为止的乘积为负数的最长子数组长度
        int[] negitive = new int[len];
        if(nums[0] > 0) {
            positive[0] = 1;
        }else if(nums[0] < 0) {
            negitive[0] = 1;
        }
        int res = positive[0];//初始化别出错
        for(int i = 1; i < len; i++) {
            if(nums[i] > 0) {
                positive[i] = positive[i - 1] + 1;
                negitive[i] = (negitive[i - 1] == 0) ? 0 : negitive[i - 1] + 1;
            }else if(nums[i] < 0) {
                positive[i] = (negitive[i - 1] == 0) ? 0 : negitive[i - 1] + 1;
                negitive[i] = positive[i - 1] + 1;
            }else if(nums[i] == 0) {
                positive[i] = 0;
                negitive[i] = 0;
            }
            res = Math.max(res, positive[i]);
        }
        System.out.println(res);
    }
}

全部评论

相关推荐

rbjjj:太杂了吧,同学,项目似乎都没深度,都是api调度耶,分层架构思想没有体现出来了,前端没有前端优化前端工程化体现,后端微服务以及分层架构没体现以及数据安全也没体现,核心再改改,注重于计算机网络,工程化,底层原理吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务