-
-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathforest000014.java
More file actions
38 lines (33 loc) ยท 1.03 KB
/
Copy pathforest000014.java
File metadata and controls
38 lines (33 loc) ยท 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
time complexity: O(n)
space complexity: O(1)
์ผ์ชฝ์์๋ถํฐ ๋์ ํฉ์ ๊ตฌํ๋, ๋ํ ๊ฐ์ด ์์๊ฐ ๋๋ ์๊ฐ ์ง๊ธ๊น์ง ๋ํ ๊ฐ์ ๋ฒ๋ฆฐ๋ค. (์ฆ, ์ง๊ธ๊น์ง์ ์์๋ ๋ชจ๋ subarray์์ ์ ์ธํ๋ค.) ์ด๋ ๊ฒ ๋์ ํฉ์ ๊ณ์ฐํ๋ฉด์, ๋์ ํฉ์ ์ต๋๊ฐ์ ์ฐพ์ผ๋ฉด ๋ต์ด ๋๋ค.
๋จ, ๋ชจ๋ ์์๊ฐ ์์์ธ ๊ฒฝ์ฐ๋ ์์ธ์ ์ผ๋ก ์ฒ๋ฆฌํด์ค๋ค.
*/
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int ans = -10001;
int max = -10001;
int sum = 0;
for (int i = 0; i < n; i++) {
if (sum + nums[i] < 0) {
sum = 0;
} else {
sum += nums[i];
}
if (sum > ans) {
ans = sum;
}
if (max < nums[i]) {
max = nums[i];
}
}
// ๋ชจ๋ ์์์ธ ๊ฒฝ์ฐ์ ์์ธ ์ฒ๋ฆฌ
if (max < 0) {
return max;
} else {
return ans;
}
}
}