-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordWrap.java
More file actions
34 lines (27 loc) · 958 Bytes
/
WordWrap.java
File metadata and controls
34 lines (27 loc) · 958 Bytes
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
package dp.commonsubsequence;
import java.util.Arrays;
public class WordWrap {
public static int solveWordWrap(int[] nums, int k) {
int[] dp = new int[nums.length];
Arrays.fill(dp, -1);
return solve(0, nums, k, dp);
}
public static int solve(int i, int[] nums, int k, int[] dp) {
if (i == nums.length) return 0;
if (dp[i] != -1) return dp[i];
int temp = 0;
int ans = Integer.MAX_VALUE;
for (int ind = i; ind < nums.length; ind++) {
if (temp + nums[ind] <= k) {
temp += nums[ind];
if (ind == nums.length - 1) ans = Math.min(ans, solve(ind + 1, nums, k, dp));
else ans = Math.min(ans, (int) Math.pow((k - temp), 2) + solve(ind + 1, nums, k, dp));
// For spaces in-between.
temp++;
} else {
break;
}
}
return dp[i] = ans;
}
}