forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmike2ox.ts
More file actions
22 lines (19 loc) ยท 783 Bytes
/
mike2ox.ts
File metadata and controls
22 lines (19 loc) ยท 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* source: https://leetcode.com/problems/maximum-subarray/
* ํ์ด๋ฐฉ๋ฒ: ํ์ฌ ์์น๊น์ง์ ์ต๋ ํฉ์ ์ ์ฅํ๋ฉด์ ์ ์ฒด ์ต๋ ํฉ์ ๊ฐฑ์
* ์๊ฐ๋ณต์ก๋: O(n) (n: nums์ ๊ธธ์ด)
* ๊ณต๊ฐ๋ณต์ก๋: O(1) (์์ ๊ณต๊ฐ๋ง ์ฌ์ฉ)
*/
function maxSubArray(nums: number[]): number {
// ๋ฐฐ์ด์ด ๋น์ด์๋ ๊ฒฝ์ฐ
if (nums.length === 0) return 0;
let result = nums[0]; // ์ ์ฒด ์ต๋ ํฉ(์ด๊ธฐ๊ฐ์ ์ฒซ ๋ฒ์งธ ์์)
let current = nums[0]; // ํ์ฌ ์์น๊น์ง์ ์ต๋ ํฉ
for (let i = 1; i < nums.length; i++) {
// ํ์ฌ ์์๋ฅผ ๋ํ ๊ฐ๊ณผ ํ์ฌ ์์ ์ค ํฐ ๊ฐ์ ์ ํ
current = Math.max(nums[i], current + nums[i]);
// ์ ์ฒด ์ต๋ ํฉ ๊ฐฑ์
result = Math.max(result, current);
}
return result;
}