Skip to content

Commit 6ec1f3d

Browse files
author
jinvicky
committed
maximum product subarray
1 parent cd9daf3 commit 6ec1f3d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public int maxProduct(int[] nums) {
3+
if (nums.length == 1)
4+
return nums[0];
5+
if (nums.length == 2) {
6+
return Math.max(nums[0], Math.max(nums[0] * nums[1], nums[1]));
7+
}
8+
9+
int len = nums.length;
10+
int[] max = new int[len];
11+
int[] min = new int[len];
12+
int overall = 0;
13+
14+
max[0] = min[0] = overall = nums[0];
15+
16+
for (int i = 1; i < len; i++) {
17+
// ํ›„๋ณด 3์„ ์ค€๋น„
18+
int justNum = nums[i];
19+
// ๊ณ„์† ๋”ํ•œ ๊ฐ’
20+
int keep = justNum * max[i-1];
21+
// ์ด์ „ ์ตœ์†Œ์— ์Œ์ˆ˜ ๊ณฑํ•ด์„œ ๋ฆฌ๋ฒ„์Šค
22+
int reverse = justNum * min[i-1];
23+
24+
// max์™€ min ๋ฐฐ์—ด์„ ์—…๋ฐ์ดํŠธ
25+
max[i] = Math.max(justNum, Math.max(keep, reverse));
26+
min[i] = Math.min(justNum, Math.min(keep, reverse));
27+
28+
// overall์„ ์—…๋ฐ์ดํŠธ, ๋ˆ„์  ๋น„๊ต๋กœ ์ตœ๋Œ€ ์ „์—ญ ์œ ์ง€
29+
overall = Math.max(overall, max[i]);
30+
}
31+
return overall;
32+
}
33+
}

0 commit comments

Comments
ย (0)