Split Array Largest Sum
題目來源
給一個陣列及一個整數m,求將陣列分割成m塊,使得這m塊中最大的和最小。
我一開始沒有理解好題目,以為是可以隨機分成m組,但是實際上每個小組是連續的。
然後最小和肯定是位於最大元素和陣列和之間的,然後進行二分,每次判斷是否可以分成m組小於mid的,假如可以,那麼mid還可以更小,假如不行,mid必須加大。
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int maxNum = 0;
long long sum = 0;
for (auto num : nums) {
sum += num;
maxNum = max(maxNum, num);
}
long long l = maxNum, r = sum;
while (l <= r) {
long long mid = (l + r) / 2;
if (valid(mid, nums, m))
r = mid - 1;
else
l = mid + 1;
}
return l;
}
bool valid(int target, vector<int>& nums, int m)
{
int count = 1;
long long total = 0;
for (auto num : nums) {
total += num;
if (total > target) {
total = num;
count++;
if (count > m)
return false;
}
}
return true;
}
};
相關文章
- Cat, Fox and Maximum Array Split
- LeetCode Kth Largest Element in an ArrayLeetCode
- 【Lintcode】576. Split Array
- [CareerCup] 18.12 Largest Sum Submatrix 和最大的子矩陣矩陣
- [CareerCup] 17.8 Contiguous Sequence with Largest Sum 連續子序列之和最大
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- Array Sum up increment. 1526, 3229REM
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- [LeetCode] Kth Largest Element in an Array (找出陣列的第k大的元素)LeetCode陣列
- LeetCode:Largest NumberLeetCode
- 2018-08-12 non-adjacent max two-number sum in loop arrayOOP
- LeetCode-Largest NumberLeetCode
- JavaScript split()JavaScript
- Awk split
- split 例子
- split partition
- Edge Split
- 《每日一題》842. Split Array into Fibonacci Sequence 將陣列拆分成斐波那契序列每日一題陣列
- 對Largest函式的測試函式
- LeetCode-Largest BST SubtreeLeetCode
- array new 與 array deletedelete
- GCD SUMGC
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- PHP array_flip() array_merge() array+array的使用總結PHP
- git subtree splitGit
- Leetcode - Largest Divisible SubsetLeetCode
- LeetCode-Largest Divisble SubsetLeetCode
- LintCode-Kth Largest Element
- Find Out Top Ten Largest Files in LinuxLinux
- Hbase split的三種方式和split的過程
- array
- leetcode15&16_3Sum&4SumLeetCode
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- 什麼是 Dynatrace 的 Largest Contentful PaintAI
- Interview-Largest independent set in binary tree.View
- php中split()用法PHP
- split相當好使