Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f4cf9ef

Browse files
solution of maximum subarray problem
1 parent 50dd147 commit f4cf9ef

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// https://leetcode.com/problems/maximum-subarray/
2+
// https://en.wikipedia.org/wiki/Maximum_subarray_problem
3+
package main
4+
5+
func maxSubArray(nums []int) int {
6+
sum := 0
7+
maxSum := -2 << 31
8+
9+
for i := 0; i < len(nums); i++ {
10+
sum = max(nums[i], sum+nums[i])
11+
maxSum = max(sum, maxSum)
12+
}
13+
14+
return maxSum
15+
}
16+
17+
func max(i, j int) int {
18+
if i > j {
19+
return i
20+
}
21+
return j
22+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// https://leetcode.com/problems/maximum-subarray/
2+
// https://en.wikipedia.org/wiki/Maximum_subarray_problem
3+
// Divide and Conquer approach
4+
package main
5+
6+
func maxSubArray(nums []int) int {
7+
n := len(nums)
8+
if n == 1 {
9+
return nums[0]
10+
}
11+
12+
mid := (n - 1) / 2
13+
14+
ans := max(maxSubArray(nums[:mid+1]), maxSubArray(nums[mid+1:]))
15+
16+
sum := 0
17+
pLeft := nums[mid]
18+
for i := mid; i >= 0; i-- {
19+
sum += nums[i]
20+
pLeft = max(pLeft, sum)
21+
}
22+
23+
pRight := nums[mid+1]
24+
sum = 0
25+
for i := mid + 1; i < n; i++ {
26+
sum += nums[i]
27+
pRight = max(pRight, sum)
28+
}
29+
30+
return max(ans, pLeft+pRight)
31+
}
32+
33+
func max(i, j int) int {
34+
if i > j {
35+
return i
36+
}
37+
return j
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /