-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCake Distribution Problem.java
More file actions
77 lines (66 loc) · 1.66 KB
/
Cake Distribution Problem.java
File metadata and controls
77 lines (66 loc) · 1.66 KB
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
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.io.*;
import java.lang.*;
class GFG{
public static void main(String [] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int test = Integer.parseInt(br.readLine());
while(test-- > 0) {
String [] str = br.readLine().trim().split(" ");
int n = Integer.parseInt(str[0]);
int k = Integer.parseInt(str[1]);
int [] sweetness = new int[n];
str = br.readLine().trim().split(" ");
int i = 0;
for(String s: str) {
sweetness[i++] = Integer.parseInt(s);
}
Solution obj = new Solution();
System.out.println(obj.maxSweetness(sweetness, n, k));
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution{
boolean isPoss(int [] sweetness, int mid, int k) {
int sum = 0;
int cnt = 0;
for (int i = 0; i < sweetness.length; i++)
{
sum += sweetness[i];
if (sum >= mid) {
cnt++;
sum = 0;
}
}
return cnt >= k + 1;
}
int maxSweetness(int [] sweetness, int n, int k) {
int sum = 0;
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
{
sum += sweetness[i];
min = Math.min(min, sweetness[i]);
}
int l = min;
int h = sum;
int ans = 0;
while (l <= h) {
int mid = (l+ h) / 2;
if (isPoss(sweetness, mid, k))
{
ans = mid;
l = mid + 1;
} else {
h = mid - 1;
}
// System.out.print(l + " " + h);
// System.out.println();
}
return ans;
}
}