Skip to content

Commit 5a5bbab

Browse files
committed
feat: Upload maximum-subarray(typescript)
1 parent 121d8ce commit 5a5bbab

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* source: https://leetcode.com/problems/maximum-subarray/
3+
* ํ’€์ด๋ฐฉ๋ฒ•: ํ˜„์žฌ ์œ„์น˜๊นŒ์ง€์˜ ์ตœ๋Œ€ ํ•ฉ์„ ์ €์žฅํ•˜๋ฉด์„œ ์ „์ฒด ์ตœ๋Œ€ ํ•ฉ์„ ๊ฐฑ์‹ 
4+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n) (n: nums์˜ ๊ธธ์ด)
5+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(1) (์ƒ์ˆ˜ ๊ณต๊ฐ„๋งŒ ์‚ฌ์šฉ)
6+
*/
7+
function maxSubArray(nums: number[]): number {
8+
// ๋ฐฐ์—ด์ด ๋น„์–ด์žˆ๋Š” ๊ฒฝ์šฐ
9+
if (nums.length === 0) return 0;
10+
11+
let result = nums[0]; // ์ „์ฒด ์ตœ๋Œ€ ํ•ฉ(์ดˆ๊ธฐ๊ฐ’์€ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ)
12+
let current = nums[0]; // ํ˜„์žฌ ์œ„์น˜๊นŒ์ง€์˜ ์ตœ๋Œ€ ํ•ฉ
13+
14+
for (let i = 1; i < nums.length; i++) {
15+
// ํ˜„์žฌ ์š”์†Œ๋ฅผ ๋”ํ•œ ๊ฐ’๊ณผ ํ˜„์žฌ ์š”์†Œ ์ค‘ ํฐ ๊ฐ’์„ ์„ ํƒ
16+
current = Math.max(nums[i], current + nums[i]);
17+
// ์ „์ฒด ์ตœ๋Œ€ ํ•ฉ ๊ฐฑ์‹ 
18+
result = Math.max(result, current);
19+
}
20+
21+
return result;
22+
}

0 commit comments

Comments
ย (0)