Skip to content

Commit d3c9c58

Browse files
committed
Solution for Maximum Subarray #275
1 parent e92b934 commit d3c9c58

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

maximum-subarray/dohyeon2.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
// TC : O(n)
3+
// SC : O(1)
4+
public int maxSubArray(int[] nums) {
5+
int max = nums[0];
6+
int sum = 0;
7+
8+
for (int i = 0; i < nums.length; i++) {
9+
// 부분합보다 현재 숫자가 더 크면 갱신한다.
10+
// 현재 숫자 단독이 더 큰 경우 이전 합이 의미가 없기 때문에 그리디하게 처리 가능
11+
sum = Math.max(nums[i], nums[i] + sum);
12+
max = Math.max(sum, max);
13+
}
14+
15+
return max;
16+
}
17+
}

0 commit comments

Comments
 (0)