Skip to content

Commit 4743850

Browse files
refactor 152
1 parent 3aa17c5 commit 4743850

File tree

1 file changed

+15
-13
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+15
-13
lines changed
Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,26 @@
11
package com.fishercoder.solutions;
22

33
/**
4-
* Find the contiguous subarray within an array (containing at least one number) which has the largest product.
4+
* 152. Maximum Product Subarray
5+
6+
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
57
68
For example, given the array [2,3,-2,4],
79
the contiguous subarray [2,3] has the largest product = 6.
810
*/
911
public class _152 {
10-
12+
public static class Solution1 {
1113
public int maxProduct(int[] nums) {
12-
int pos = nums[0];
13-
int neg = nums[0];
14-
int max = nums[0];
15-
for (int i = 1; i < nums.length; i++) {
16-
int temp = pos;
17-
pos = Math.max(nums[i], nums[i] * ((nums[i] >= 0) ? pos : neg));
18-
neg = Math.min(nums[i], nums[i] * ((nums[i] >= 0) ? neg : temp));
19-
max = Math.max(max, pos);
20-
}
21-
return max;
14+
int pos = nums[0];
15+
int neg = nums[0];
16+
int max = nums[0];
17+
for (int i = 1; i < nums.length; i++) {
18+
int temp = pos;
19+
pos = Math.max(nums[i], nums[i] * ((nums[i] >= 0) ? pos : neg));
20+
neg = Math.min(nums[i], nums[i] * ((nums[i] >= 0) ? neg : temp));
21+
max = Math.max(max, pos);
22+
}
23+
return max;
2224
}
23-
25+
}
2426
}

0 commit comments

Comments
 (0)