Skip to content

Commit 0a28c5f

Browse files
add: maximum sub list
1 parent 4abe480 commit 0a28c5f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

maximum-subarray/YoungSeok-Choi.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
// NOTE: 카데인 알고리즘.
3+
// TODO: O(n^2) 복잡도의 브루트포스 방식으로도 풀어보기.
4+
class Solution {
5+
public int maxSubArray(int[] nums) {
6+
7+
int maxSum = nums[0];
8+
int curSum = nums[0];
9+
10+
for (int i = 1; i < nums.length; i++) {
11+
curSum = Math.max(nums[i], curSum + nums[i]);
12+
maxSum = Math.max(maxSum, curSum);
13+
}
14+
15+
return maxSum;
16+
}
17+
}
18+
19+
// NOTE: 시작점 변경의 조건(?)을 제대로 정의하지 못해 틀린문제..
20+
// 답지 보고 해결....
21+
class WrongSolution {
22+
public int maxSubArray(int[] nums) {
23+
int gMax = -123456789;
24+
int curMax = -123456789;
25+
int curSum = 0;
26+
27+
for(int i = 0; i < nums.length; i++) {
28+
if(curMax < nums[i]) {
29+
// 시작점 변경.
30+
curSum = nums[i];
31+
curMax = nums[i];
32+
} else {
33+
curSum += nums[i];
34+
curMax = Math.max(curMax, curSum);
35+
}
36+
37+
gMax = Math.max(gMax, curMax);
38+
}
39+
40+
return gMax;
41+
}
42+
43+
}

0 commit comments

Comments
 (0)