Skip to content

Commit 5cdfab5

Browse files
committed
feat: maximum-subarray solution
1 parent f436166 commit 5cdfab5

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

maximum-subarray/YeomChaeeun.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* 연속되는 서브 배열로 최대 합을 구하기
3+
* 알고리즘 복잡도
4+
* - 시간 복잡도: O(n)
5+
* - 공간 복잡도: O(1)
6+
* @param nums
7+
*/
8+
function maxSubArray(nums: number[]): number {
9+
if(nums.length === 1) return nums[0]
10+
11+
let currentSum = nums[0]
12+
let maxSum = nums[0]
13+
for(let i = 1; i < nums.length; i++) {
14+
currentSum = Math.max(nums[i], currentSum + nums[i])
15+
// 최대값 갱신
16+
maxSum = Math.max(maxSum, currentSum)
17+
}
18+
19+
return maxSum
20+
}

0 commit comments

Comments
 (0)