-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
410. 分割数组的最大值 #48
Comments
Go这种使...最大值最小是二分查找常见的问题,下面来说一下思路:
我们可以从 func splitArray(nums []int, m int) int {
left, right := 0, 0
for _, v := range nums {
right += v
if left < v {
left = v
}
}
for left < right {
mid := (left + right) / 2
subSum, cnt := 0, 1
for _, v := range nums {
if subSum+v > mid {
subSum = v
cnt++
} else {
subSum += v
}
}
if cnt > m {
left = mid + 1
} else {
right = mid
}
}
return left
} |
JS/**
* @param {number[]} nums
* @param {number} m
* @return {number}
*/
var splitArray = function(nums, m) {
let left = 0, right = 0;
for (let i = 0; i < nums.length; i++) {
right += nums[i];
if (left < nums[i]) {
left = nums[i];
}
}
while (left < right) {
let mid = Math.floor((left + right) / 2);
let subSum = 0, cnt = 1;
for (let i = 0; i < nums.length; i++) {
if (subSum + nums[i] > mid) {
subSum = nums[i];
cnt++;
} else {
subSum += nums[i];
}
}
if (cnt > m) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
注意:
数组长度 n 满足以下条件:
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-array-largest-sum
The text was updated successfully, but these errors were encountered: