Skip to content

Commit 5118c0d

Browse files
committed
maximum subarray solution
1 parent b433c11 commit 5118c0d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

β€Žmaximum-subarray/smosco.jsβ€Ž

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Maximum Subarray - 브루트포슀 (완전탐색)
3+
*
4+
* 핡심 아이디어:
5+
* - λͺ¨λ“  κ°€λŠ₯ν•œ 연속 λΆ€λΆ„ λ°°μ—΄μ˜ 합을 κ³„μ‚°ν•˜μ—¬ μ΅œλŒ“κ°’ μ°ΎκΈ°
6+
* - iλ²ˆμ§ΈλΆ€ν„° jλ²ˆμ§ΈκΉŒμ§€μ˜ 합을 λˆ„μ ν•˜λ©΄μ„œ 계산
7+
*
8+
* μ‹œκ°„ λ³΅μž‘λ„: O(nΒ²) - 이쀑 반볡문으둜 λͺ¨λ“  ꡬ간 탐색
9+
* 곡간 λ³΅μž‘λ„: O(1) - λ³€μˆ˜ λͺ‡ 개만 μ‚¬μš©
10+
*/
11+
const maxSubArray = (nums) => {
12+
const n = nums.length;
13+
let maxSoFar = nums[0];
14+
15+
for (let i = 0; i < n; i++) {
16+
let currentSum = 0;
17+
for (let j = i; j < n; j++) {
18+
currentSum += nums[j]; // iλΆ€ν„° jκΉŒμ§€μ˜ λˆ„μ  ν•©
19+
maxSoFar = Math.max(maxSoFar, currentSum);
20+
}
21+
}
22+
23+
return maxSoFar;
24+
};
25+
26+
/**
27+
* Maximum Subarray - Kadane's Algorithm
28+
*
29+
* 핡심 아이디어:
30+
* - 각 μœ„μΉ˜μ—μ„œ "ν˜„μž¬ 숫자만으둜 μƒˆλ‘œ μ‹œμž‘ vs 이전 합에 ν˜„μž¬ 숫자 μΆ”κ°€" 쀑 더 큰 κ°’ 선택
31+
* - currentMax = max(ν˜„μž¬ 숫자, μ§€κΈˆκΉŒμ§€ ν•© + ν˜„μž¬ 숫자)
32+
* - 즉, μ΄μ „κΉŒμ§€μ˜ 합이 ν˜„μž¬μ— 도움이 μ•ˆ 되면 버리고 μƒˆλ‘œ μ‹œμž‘
33+
*
34+
* μ‹œκ°„ λ³΅μž‘λ„: O(n) - 배열을 ν•œ 번만 순회
35+
* 곡간 λ³΅μž‘λ„: O(1) - λ³€μˆ˜ 두 개만 μ‚¬μš©
36+
*/
37+
const maxSubArrayKadane = (nums) => {
38+
let currentMax = nums[0]; // ν˜„μž¬ μœ„μΉ˜κΉŒμ§€μ˜ μ΅œλŒ€ ν•©
39+
let globalMax = nums[0]; // 전체 μ΅œλŒ€ ν•©
40+
41+
for (let i = 1; i < nums.length; i++) {
42+
// 핡심: 이전 합에 더할지 vs μƒˆλ‘œ μ‹œμž‘ν• μ§€
43+
currentMax = Math.max(nums[i], currentMax + nums[i]);
44+
globalMax = Math.max(globalMax, currentMax);
45+
}
46+
47+
return globalMax;
48+
};

0 commit comments

Comments
Β (0)