Skip to content

Commit d2eb309

Browse files
committed
maximium subarray solution
1 parent c37eac9 commit d2eb309

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int maxSubArray(int[] nums) {
3+
/**
4+
1. ๋ฌธ์ œ: ๊ฐ€์žฅ ํฐ ํ•ฉ์„ ๊ฐ€์ง€๋Š” subarray ์˜ sum ์„ ๋ฐ˜ํ™˜
5+
2. ์กฐ๊ฑด: ์›์†Œ๊ฐ’์€ ์Œ์ˆ˜ ~ ์–‘์ˆ˜, ๋ฐฐ์—ด ์ตœ๋Œ€ ๊ธธ์ด = 10^5, ์ตœ์†Œ ๊ธธ์ด = 1
6+
- time complexity: O(N)
7+
- space complexity: O(1)
8+
*/
9+
10+
if (nums.length == 1) {
11+
return nums[0];
12+
}
13+
14+
int maxSum = nums[0]; //์ „์ฒด ์ตœ๋Œ€
15+
int curSum = nums[0]; //ํ˜„์žฌ ํ•ฉ
16+
17+
for(int i = 1; i<nums.length; i++) {
18+
curSum = Math.max(nums[i], curSum + nums[i]);
19+
maxSum = Math.max(maxSum, curSum);
20+
}
21+
return maxSum;
22+
}
23+
}

0 commit comments

Comments
ย (0)