Skip to content

Commit 70fe878

Browse files
authored
Create painter’s partition problem.cpp
1 parent 1d9f03f commit 70fe878

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// A DP based CPP program for painter's partition problem
2+
#include <climits>
3+
#include <iostream>
4+
using namespace std;
5+
6+
// function to calculate sum between two indices
7+
// in array
8+
int sum(int arr[], int from, int to)
9+
{
10+
int total = 0;
11+
for (int i = from; i <= to; i++)
12+
total += arr[i];
13+
return total;
14+
}
15+
16+
// bottom up tabular dp
17+
int findMax(int arr[], int n, int k)
18+
{
19+
// initialize table
20+
int dp[k + 1][n + 1] = { 0 };
21+
22+
// base cases
23+
// k=1
24+
for (int i = 1; i <= n; i++)
25+
dp[1][i] = sum(arr, 0, i - 1);
26+
27+
// n=1
28+
for (int i = 1; i <= k; i++)
29+
dp[i][1] = arr[0];
30+
31+
// 2 to k partitions
32+
for (int i = 2; i <= k; i++) { // 2 to n boards
33+
for (int j = 2; j <= n; j++) {
34+
35+
// track minimum
36+
int best = INT_MAX;
37+
38+
// i-1 th separator before position arr[p=1..j]
39+
for (int p = 1; p <= j; p++)
40+
best = min(best, max(dp[i - 1][p],
41+
sum(arr, p, j - 1)));
42+
43+
dp[i][j] = best;
44+
}
45+
}
46+
47+
// required
48+
return dp[k][n];
49+
}
50+
51+
// driver function
52+
int main()
53+
{
54+
int arr[] = { 10, 20, 60, 50, 30, 40 };
55+
int n = sizeof(arr) / sizeof(arr[0]);
56+
int k = 3;
57+
cout << findMax(arr, n, k) << endl;
58+
return 0;
59+
}

0 commit comments

Comments
 (0)