Skip to content

Commit

Permalink
go implementation. binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed May 11, 2019
1 parent 4fa6797 commit 0dc94b0
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 410. Split Array Largest Sum/split_array_largest_sum.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package problem410

func max(nums ...int) int {
max := nums[0]
for _, x := range nums {
if x > max {
max = x
}
}
return max
}

func sum(nums []int) int {
res := 0
for _, x := range nums {
res += x
}
return res
}

func split(nums []int, capacity int) int {
count := 1
pack := 0
for _, x := range nums {
pack += x
if pack > capacity {
pack = x
count++
}
}
return count
}

func splitArray(nums []int, m int) int {
left := max(nums...)
right := sum(nums)
var mid int
for left < right {
mid = (left + right) / 2
if split(nums, mid) > m {
left = mid + 1
} else {
right = mid
}
}
return left
}

0 comments on commit 0dc94b0

Please sign in to comment.