-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion20.java
More file actions
34 lines (24 loc) · 920 Bytes
/
question20.java
File metadata and controls
34 lines (24 loc) · 920 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class question20 {
public static int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int maxProduct = nums[0];
int minProduct = nums[0];
int result = nums[0];
for (int i = 1; i < nums.length; i++) {
int current = nums[i];
if (current < 0) {
int temp = maxProduct;
maxProduct = minProduct;
minProduct = temp;
}
maxProduct = Math.max(current, current * maxProduct);
minProduct = Math.min(current, current * minProduct);
result = Math.max(result, maxProduct);
}
return result;
}
public static void main(String[] args) {
int[] nums = {2, 3, -2, 4};
System.out.println("Maximum Product Subarray: " + maxProduct(nums));
}
}