-
-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathforest000014.java
More file actions
38 lines (33 loc) Β· 1.03 KB
/
forest000014.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;
}
}
}