-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaintersPartition.cpp
77 lines (64 loc) · 1.26 KB
/
PaintersPartition.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
#include <iostream>
#include <vector>
using namespace std;
bool isPossible(vector<int> &arr, int n, int m, int maxAllowedTime)
{
int painters = 1, time = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] > maxAllowedTime)
{
return false;
}
if (time + arr[i] <= maxAllowedTime)
{
time += arr[i];
}
else
{
painters++;
time = arr[i];
}
}
return painters <= m;
}
int minTimeToPaint(vector<int> &arr, int n, int m) // O(log(sum) * n)
{
if (m > n)
{
return -1;
}
int sum = 0;
int largest = arr[0];
for (int i = 0; i < n; i++)
{
sum += arr[i];
if (arr[i] > largest)
{
largest = arr[i];
}
}
int st = largest, end = sum; // range of possible answers
int ans = -1;
while (st <= end)
{
int mid = st + (end - st) / 2;
if (isPossible(arr, n, m, mid))
{
ans = mid;
end = mid - 1;
}
else
{
st = mid + 1;
}
}
return ans;
}
int main()
{
vector<int> arr = {40, 30, 10, 20};
int n = 4, m = 2;
cout << minTimeToPaint(arr, n, m) << endl;
return 0;
}