Skip to content

Commit b5934f4

Browse files
committed
add: 分割数组的最大值
1 parent ee3b346 commit b5934f4

File tree

5 files changed

+73
-1
lines changed

5 files changed

+73
-1
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文
206206

207207
### 数组/队列/集合/映射
208208

209+
- [分割数组的最大值](src/array/split_array_largest_sum.cpp) [贪心, 数组, 二分查找, 动态规划, 前缀和]
210+
211+
- LeetCode 410. 分割数组的最大值 <https://leetcode.cn/problems/split-array-largest-sum>
212+
209213
- [按分隔符拆分字符串](src/array/split_strings_by_separator.cpp) [数组, 字符串]
210214

211215
- LeetCode 2788. 按分隔符拆分字符串 <https://leetcode.cn/problems/split-strings-by-separator>
70.5 KB
Loading

src/array/split_array_largest_sum.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// 分割数组的最大值
2+
// https://leetcode.cn/problems/split-array-largest-sum
3+
// INLINE ../../images/array/split_array_largest_sum.jpeg
4+
5+
#include <headers.hpp>
6+
7+
class Solution {
8+
public:
9+
int split(vector<int> &nums, int max) {
10+
int count = 1;
11+
int sum = 0;
12+
for (int num : nums) {
13+
if (sum + num > max) {
14+
count++;
15+
sum = num;
16+
} else {
17+
sum += num;
18+
}
19+
}
20+
return count;
21+
}
22+
int splitArray(vector<int> &nums, int k) {
23+
int left = 0, right = 0;
24+
for (int num : nums) {
25+
left = max(left, num);
26+
right += num;
27+
}
28+
while (left < right) {
29+
int mid = left + (right - left) / 2;
30+
int count = split(nums, mid);
31+
if (count <= k) {
32+
right = mid;
33+
} else {
34+
left = mid + 1;
35+
}
36+
}
37+
return left;
38+
}
39+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <array/split_array_largest_sum.cpp>
2+
3+
TEST(分割数组的最大值, splitArray) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:nums = [7,2,5,10,8], k = 2
7+
// 输出:18
8+
// 解释:
9+
// 一共有四种方法将 nums 分割为 2 个子数组。
10+
// 其中最好的方式是将其分为 [7,2,5] 和 [10,8] 。
11+
// 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。
12+
vector<int> nums = {7, 2, 5, 10, 8};
13+
int k = 2;
14+
EXPECT_EQ(solution.splitArray(nums, k), 18);
15+
16+
// 示例 2:
17+
// 输入:nums = [1,2,3,4,5], k = 2
18+
// 输出:9
19+
vector<int> nums2 = {1, 2, 3, 4, 5};
20+
int k2 = 2;
21+
EXPECT_EQ(solution.splitArray(nums2, k2), 9);
22+
23+
// 示例 3:
24+
// 输入:nums = [1,4,4], k = 3
25+
// 输出:4
26+
vector<int> nums3 = {1, 4, 4};
27+
int k3 = 3;
28+
EXPECT_EQ(solution.splitArray(nums3, k3), 4);
29+
}

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2024-01-20 23:28:50
1+
// 执行编译时间:2024-01-21 14:50:51
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

0 commit comments

Comments
 (0)