Skip to content

Commit 9c1fff6

Browse files
committed
Maximum Subarray
1 parent 9c068d6 commit 9c1fff6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
time complexity: O(n)
3+
space complexity: O(1)
4+
5+
μ™Όμͺ½μ—μ„œλΆ€ν„° λˆ„μ ν•©μ„ κ΅¬ν•˜λ˜, λ”ν•œ 값이 μŒμˆ˜κ°€ λ˜λŠ” μˆœκ°„ μ§€κΈˆκΉŒμ§€ λ”ν•œ 값을 버린닀. (즉, μ§€κΈˆκΉŒμ§€μ˜ μ›μ†ŒλŠ” λͺ¨λ‘ subarrayμ—μ„œ μ œμ™Έν•œλ‹€.) μ΄λ ‡κ²Œ λˆ„μ ν•©μ„ κ³„μ‚°ν•˜λ©΄μ„œ, λˆ„μ ν•©μ˜ μ΅œλŒ€κ°’μ„ 찾으면 닡이 λœλ‹€.
6+
7+
단, λͺ¨λ“  μ›μ†Œκ°€ 음수인 κ²½μš°λŠ” μ˜ˆμ™Έμ μœΌλ‘œ μ²˜λ¦¬ν•΄μ€€λ‹€.
8+
9+
*/
10+
11+
class Solution {
12+
public int maxSubArray(int[] nums) {
13+
int n = nums.length;
14+
int ans = -10001;
15+
int max = -10001;
16+
int sum = 0;
17+
for (int i = 0; i < n; i++) {
18+
if (sum + nums[i] < 0) {
19+
sum = 0;
20+
} else {
21+
sum += nums[i];
22+
}
23+
if (sum > ans) {
24+
ans = sum;
25+
}
26+
if (max < nums[i]) {
27+
max = nums[i];
28+
}
29+
}
30+
31+
// λͺ¨λ‘ 음수인 경우의 μ˜ˆμ™Έ 처리
32+
if (max < 0) {
33+
return max;
34+
} else {
35+
return ans;
36+
}
37+
}
38+
}

0 commit comments

Comments
Β (0)