File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments