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;
}
};
相關文章
- LeetCode Kth Largest Element in an ArrayLeetCode
- 215. Kth Largest Element in an Array
- Cat, Fox and Maximum Array Split
- 【Lintcode】576. Split Array
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- Array Sum up increment. 1526, 3229REM
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- 2018-08-12 non-adjacent max two-number sum in loop arrayOOP
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- 《每日一題》842. Split Array into Fibonacci Sequence 將陣列拆分成斐波那契序列每日一題陣列
- leetcode 368. Largest Divisible SubsetLeetCode
- JavaScript split()JavaScript
- Edge Split
- 對Largest函式的測試函式
- Hbase split的三種方式和split的過程
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- GCD SUMGC
- Sum Problem
- 集合sum
- 515-Find Largest Value in Each Tree Row
- 什麼是 Dynatrace 的 Largest Contentful PaintAI
- 15+18、3Sum 4Sum
- java split用法 案例Java
- os.path.split
- php中的chunk_split()和str_split()字串函式PHP字串函式
- Array.from和 Array.of
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- leetcode Sum系列LeetCode
- Sum of Left Leaves
- Path-sum
- Path Sum III
- Leetcode Path SumLeetCode
- B - Minimum Sum
- Range Minimum Sum
- Missing Subsequence Sum
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- Array()與Array.of()方法區別