题解 | #乘积为正数的最长连续子数组#
乘积为正数的最长连续子数组
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); //以i结尾且必须包含i int n = in.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) nums[i] = in.nextInt(); int[] ps = new int[n]; int[] ns = new int[n]; ps[0] = nums[0] > 0 ? 1 : 0; ns[0] = nums[0] < 0 ? 1 : 0; int res = ps[0]; for (int i = 1; i < n; i++) { if (nums[i] > 0) { ps[i] = ps[i - 1] + 1; ns[i] = ns[i - 1] > 0 ? ns[i - 1] + 1 : 0; } else if (nums[i] < 0) { ps[i] = ns[i - 1] > 0 ? ns[i - 1] + 1 : 0; ns[i] = ps[i - 1] + 1; } else { ps[i] = 0; ns[i] = 0; } res = Math.max(res, ps[i]); } System.out.print(res); } }