Skip to content

Commit 4a9f60a

Browse files
authored
Create split-array-largest-sum.cpp
1 parent 2d4e24b commit 4a9f60a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

C++/split-array-largest-sum.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(nlogn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int splitArray(vector<int>& nums, int m) {
7+
int left = 0, right = 0;
8+
for (const auto& num : nums) {
9+
left = max(left, num);
10+
right += num;
11+
}
12+
13+
while (left <= right) {
14+
int mid = left + (right - left) / 2;
15+
if (canSplit(nums, m, mid)) {
16+
right = mid - 1;
17+
} else {
18+
left = mid + 1;
19+
}
20+
}
21+
return left;
22+
}
23+
24+
private:
25+
bool canSplit(vector<int>& nums, int m, int sum) {
26+
int cnt = 1;
27+
int curr_sum = 0;
28+
for (const auto& num : nums) {
29+
curr_sum += num;
30+
if (curr_sum > sum) {
31+
curr_sum = num;
32+
++cnt;
33+
}
34+
}
35+
return cnt <= m;
36+
}
37+
};

0 commit comments

Comments
 (0)