Skip to content

Commit d304655

Browse files
committed
Solution: Maximum Subarray
1 parent 50d78a0 commit d304655

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

maximum-subarray/flynn.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
풀이 1
3+
- 아래와 같은 memo 배열을 만들어서 풀이할 수 있습니다 (참고: Kadane's Algorithm)
4+
memo[i] = nums[:i] 중에서 nums[i]를 반드시 포함하는 부분 배열의 최대 합
5+
6+
Big O
7+
- N: 주어진 배열 nums의 길이
8+
- Time complexity: O(N)
9+
- Space complexity: O(N)
10+
*/
11+
12+
func maxSubArray(nums []int) int {
13+
n := len(nums)
14+
15+
memo := make([]int, n)
16+
copy(memo, nums)
17+
18+
maxSum := nums[0]
19+
20+
for i := 1; i < n; i++ {
21+
if memo[i-1] > 0 {
22+
memo[i] += memo[i-1]
23+
}
24+
25+
if maxSum < memo[i] {
26+
maxSum = memo[i]
27+
}
28+
}
29+
30+
return maxSum
31+
}
32+
33+
/*
34+
풀이 2
35+
- 알고리즘의 전개 과정을 보면 O(N)의 공간복잡도를 갖는 memo가 필요하지 않다는 걸 알 수 있습니다
36+
- memo 배열 대신 현재 계산 중인 부분 배열의 합만 계속 갱신합니다
37+
38+
Big O
39+
- N: 주어진 배열 nums의 길이
40+
- Time complexity: O(N)
41+
- Space complexity: O(1)
42+
*/
43+
44+
func maxSubArray(nums []int) int {
45+
maxSum, currSum := nums[0], nums[0]
46+
47+
for i := 1; i < len(nums); i++ {
48+
if currSum > 0 {
49+
currSum += nums[i]
50+
} else {
51+
currSum = nums[i]
52+
}
53+
54+
if maxSum < currSum {
55+
maxSum = currSum
56+
}
57+
}
58+
59+
return maxSum
60+
}

0 commit comments

Comments
 (0)