|
1 | 1 | packagecom.fishercoder.solutions; |
2 | 2 |
|
3 | | -/** |
4 | | - * 152. Maximum Product Subarray |
5 | | -
|
6 | | - Find the contiguous subarray within an array (containing at least one number) which has the largest product. |
7 | | -
|
8 | | - For example, given the array [2,3,-2,4], |
9 | | - the contiguous subarray [2,3] has the largest product = 6. |
10 | | - */ |
11 | 3 | publicclass_152 { |
12 | | -publicstaticclassSolution1 { |
13 | | -publicintmaxProduct(int[]nums) { |
14 | | -intpos =nums[0]; |
15 | | -intneg =nums[0]; |
16 | | -intmax =nums[0]; |
17 | | -for (inti =1;i <nums.length;i++) { |
18 | | -inttemp =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 | | -returnmax; |
| 4 | +publicstaticclassSolution1 { |
| 5 | +publicintmaxProduct(int[]nums) { |
| 6 | +intpos =nums[0]; |
| 7 | +intneg =nums[0]; |
| 8 | +intmax =nums[0]; |
| 9 | +for (inti =1;i <nums.length;i++) { |
| 10 | +inttemp =pos; |
| 11 | +pos =Math.max(nums[i],nums[i] * ((nums[i] >=0) ?pos :neg)); |
| 12 | +neg =Math.min(nums[i],nums[i] * ((nums[i] >=0) ?neg :temp)); |
| 13 | +max =Math.max(max,pos); |
| 14 | + } |
| 15 | +returnmax; |
| 16 | + } |
24 | 17 | } |
25 | | - } |
26 | 18 | } |