-
Notifications
You must be signed in to change notification settings - Fork 0
/
split_array_largest_sum.cpp
94 lines (86 loc) · 1.98 KB
/
split_array_largest_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// =====================================================================================
//
// Filename: split_array_largest_sum.cpp
//
// Description: 410. Split Array Largest Sum.
//
// Version: 1.0
// Created: 11/14/2019 12:54:33 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <stdint.h>
#include <algorithm>
#include <vector>
using std::vector;
// Binary search
class Solution
{
public:
int splitArray(vector<int>& nums, int m)
{
int64_t sum = 0;
int max_num = 0;
for (auto num: nums)
{
sum += num;
max_num = std::max(max_num, num);
}
if (m == 1)
{
return sum;
}
if (m >= nums.size() - 1)
{
return max_num;
}
int64_t left = max_num;
int64_t right = sum;
while (left <= right)
{
int64_t middle = (left + right) / 2;
if (isValid(nums, m, middle))
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return (int)left;
}
private:
bool isValid(vector<int>& nums, int m, int target)
{
int sum = 0;
int count = 1;
for (auto num: nums)
{
sum += num;
if (sum > target)
{
sum = num;
count++;
if (count > m)
{
return false;
}
}
}
return true;
}
};
int main(int argc, char* argv[])
{
vector<int> nums = {7, 2, 5, 10, 8};
int m = 2;
int largest = Solution().splitArray(nums, m);
printf("The minimize the largest sum is %d\n", largest);
return 0;
}