Skip to content

Commit 09beca4

Browse files
authored
sadie100: maximum subarray solution
1 parent e86ed20 commit 09beca4

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

maximum-subarray/sadie100.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
nums를 순회하며 최대 sum을 찾는다. 다음 규칙을 따른다
3+
- 매 순간 숫자를 더해 가며 현재까지의 합과 최대합 비교, 갱신
4+
- 만약 해당 인덱스 num을 더했을 때 0보다 작아지면 현재까지의 값을 0으로 초기화(총합 버림)
5+
6+
*/
7+
8+
function maxSubArray(nums: number[]): number {
9+
let result = -Infinity;
10+
let curSum = 0;
11+
12+
for (let num of nums) {
13+
curSum += num;
14+
result = Math.max(result, curSum);
15+
if (curSum < 0) curSum = 0;
16+
}
17+
18+
return result;
19+
}

0 commit comments

Comments
 (0)