Skip to content

Commit

Permalink
add: 分割数组的最大值
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Jan 21, 2024
1 parent ee3b346 commit b5934f4
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文

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

- [分割数组的最大值](src/array/split_array_largest_sum.cpp) [贪心, 数组, 二分查找, 动态规划, 前缀和]

- LeetCode 410. 分割数组的最大值 <https://leetcode.cn/problems/split-array-largest-sum>

- [按分隔符拆分字符串](src/array/split_strings_by_separator.cpp) [数组, 字符串]

- LeetCode 2788. 按分隔符拆分字符串 <https://leetcode.cn/problems/split-strings-by-separator>
Expand Down
Binary file added images/array/split_array_largest_sum.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions src/array/split_array_largest_sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 分割数组的最大值
// https://leetcode.cn/problems/split-array-largest-sum
// INLINE ../../images/array/split_array_largest_sum.jpeg

#include <headers.hpp>

class Solution {
public:
int split(vector<int> &nums, int max) {
int count = 1;
int sum = 0;
for (int num : nums) {
if (sum + num > max) {
count++;
sum = num;
} else {
sum += num;
}
}
return count;
}
int splitArray(vector<int> &nums, int k) {
int left = 0, right = 0;
for (int num : nums) {
left = max(left, num);
right += num;
}
while (left < right) {
int mid = left + (right - left) / 2;
int count = split(nums, mid);
if (count <= k) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
29 changes: 29 additions & 0 deletions test/array/split_array_largest_sum_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <array/split_array_largest_sum.cpp>

TEST(分割数组的最大值, splitArray) {
Solution solution;
// 示例 1:
// 输入:nums = [7,2,5,10,8], k = 2
// 输出:18
// 解释:
// 一共有四种方法将 nums 分割为 2 个子数组。
// 其中最好的方式是将其分为 [7,2,5] 和 [10,8] 。
// 因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。
vector<int> nums = {7, 2, 5, 10, 8};
int k = 2;
EXPECT_EQ(solution.splitArray(nums, k), 18);

// 示例 2:
// 输入:nums = [1,2,3,4,5], k = 2
// 输出:9
vector<int> nums2 = {1, 2, 3, 4, 5};
int k2 = 2;
EXPECT_EQ(solution.splitArray(nums2, k2), 9);

// 示例 3:
// 输入:nums = [1,4,4], k = 3
// 输出:4
vector<int> nums3 = {1, 4, 4};
int k3 = 3;
EXPECT_EQ(solution.splitArray(nums3, k3), 4);
}
2 changes: 1 addition & 1 deletion test/lib/lib_test.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 执行编译时间:2024-01-20 23:28:50
// 执行编译时间:2024-01-21 14:50:51
#include <gtest/gtest.h>
#include <lib.hpp>

Expand Down

0 comments on commit b5934f4

Please sign in to comment.