-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordWrap.java
More file actions
48 lines (39 loc) · 1.22 KB
/
WordWrap.java
File metadata and controls
48 lines (39 loc) · 1.22 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
import java.util.Arrays;
public class WordWrap {
static int dp[][] = new int[5][8];
public static int rec(int i,int rem, int[] arr, int k){
if(i==arr.length+1){
return 0;
}
if(dp[i][rem]!=-1){
return dp[i][rem];
}
int ans;
if(arr[i-1] > rem-1){
ans = (rem)*(rem) + rec(i+1, k-arr[i-1]-1, arr, k);
}
else{
int choice1 = (rem)*(rem) + rec(i+1, k-arr[i-1]-1, arr, k);
int choice2 = rec(i+1,rem-arr[i-1]-1, arr, k);
ans =(int)(Math.min(choice1,choice2));
}
dp[i][rem] = ans;
return dp[i][rem];
}
public static int solveWordWrap(int[] nums, int k){
for(int[] col:dp)
Arrays.fill(col, -1);
return rec(1,k+1, nums, k+1);
}
public static void main(String args[]){
int nums[]={3,2,2,5};
int k=6;
int ans = solveWordWrap(nums, k);
System.out.println(ans);
for(int[] col:dp){
for(int row:col)
System.out.print(row+ " ");
System.out.println();
}
}
}