File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed 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