题解 | #乘积为正数的最长连续子数组#
乘积为正数的最长连续子数组
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); } }