forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneverlish.go
More file actions
51 lines (35 loc) ยท 783 Bytes
/
neverlish.go
File metadata and controls
51 lines (35 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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// ์๊ฐ๋ณต์ก๋: O(n)
// ๊ณต๊ฐ๋ณต์ก๋: O(n)
package main
import "testing"
func TestMaxSubArray(t *testing.T) {
result1 := maxSubArray([]int{-2,1,-3,4,-1,2,1,-5,4})
if result1 != 6 {
t.Errorf("Expected 6, got %d", result1)
}
result2 := maxSubArray([]int{1})
if result2 != 1 {
t.Errorf("Expected 1, got %d", result2)
}
result3 := maxSubArray([]int{5,4,-1,7,8})
if result3 != 23 {
t.Errorf("Expected 23, got %d", result3)
}
}
func max(nums ...int) int {
result := nums[0]
for _, num := range nums[1:] {
if num > result {
result = num
}
}
return result
}
func maxSubArray(nums []int) int {
dp := make([]int, len(nums))
dp[0] = nums[0]
for index, num := range nums[1:] {
dp[index+1] = max(0, dp[index]) + num
}
return max(dp...)
}