Skip to content

Commit fd7e081

Browse files
committed
Minimize Maximum Partition Sum
1 parent f3cf1b7 commit fd7e081

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
This problem was asked by **Etsy**.
2+
3+
Given an array of numbers N and an integer k, your task is to split N into k partitions such that the maximum sum of any partition is minimized. Return this sum.
4+
5+
For example, given N = [5, 1, 2, 7, 3, 4] and k = 3, you should return 8, since the optimal partition is [5, 1, 2], [7], [3, 4].
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
public class Approach1 {
2+
3+
public static void main(String[] args) {
4+
int[] N = {5, 1, 2, 7, 3, 4};
5+
int k = 3;
6+
System.out.println(minimizeMaxPartitionSum(N, k)); // Output: 8
7+
}
8+
9+
public static int minimizeMaxPartitionSum(int[] N, int k) {
10+
int left = findMax(N);
11+
int right = sumArray(N);
12+
13+
while (left < right) {
14+
int mid = left + (right - left) / 2;
15+
if (canPartition(N, k, mid)) {
16+
right = mid;
17+
} else {
18+
left = mid + 1;
19+
}
20+
}
21+
22+
return left;
23+
}
24+
25+
private static int findMax(int[] N) {
26+
int max = Integer.MIN_VALUE;
27+
for (int num : N) {
28+
if (num > max) {
29+
max = num;
30+
}
31+
}
32+
return max;
33+
}
34+
35+
private static int sumArray(int[] N) {
36+
int sum = 0;
37+
for (int num : N) {
38+
sum += num;
39+
}
40+
return sum;
41+
}
42+
43+
private static boolean canPartition(int[] N, int k, int maxSum) {
44+
int currentSum = 0;
45+
int requiredPartitions = 1;
46+
47+
for (int num : N) {
48+
if (currentSum + num > maxSum) {
49+
requiredPartitions++;
50+
currentSum = num;
51+
if (requiredPartitions > k) {
52+
return false;
53+
}
54+
} else {
55+
currentSum += num;
56+
}
57+
}
58+
59+
return true;
60+
}
61+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function minimizeMaxPartitionSum(N, k) {
2+
let left = Array.max(N);
3+
let right = Array.sum(N);
4+
5+
while (left < right) {
6+
let mid = left + Math.floor((right - left) / 2);
7+
if (canPartition(N, k, mid)) {
8+
right = mid;
9+
} else {
10+
left = mid + 1;
11+
}
12+
}
13+
14+
return left;
15+
}
16+
17+
function canPartition(N, k, maxSum) {
18+
let currentSum = 0;
19+
let requiredPartitions = 1;
20+
21+
for (let num of N) {
22+
if (currentSum + num > maxSum) {
23+
requiredPartitions++;
24+
currentSum = num;
25+
if (requiredPartitions > k) {
26+
return false;
27+
}
28+
} else {
29+
currentSum += num;
30+
}
31+
}
32+
33+
return true;
34+
}
35+
36+
let N = [5, 1, 2, 7, 3, 4];
37+
let k = 3;
38+
console.log(minimizeMaxPartitionSum(N, k));

0 commit comments

Comments
 (0)