-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgrammers_389480.java
More file actions
59 lines (49 loc) · 1.62 KB
/
Copy pathProgrammers_389480.java
File metadata and controls
59 lines (49 loc) · 1.62 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
package programmers.lv2;
import java.util.Arrays;
public class Programmers_389480 {
public static void main(String[] args) {
Programmers_389480 test = new Programmers_389480();
int[][] info = { { 1, 2 }, { 2, 3 }, { 2, 1 } };
int n = 4;
int m = 4;
int result = test.solution(info, n, m);
System.out.println("result: " + result);
}
public int solution(int[][] info, int n, int m) {
int len = info.length;
int maxValue = Integer.MAX_VALUE;
int[][] dp = new int[len + 1][m];
for (int i = 0; i <= len; i++) {
Arrays.fill(dp[i], maxValue);
}
dp[0][0] = 0;
for (int i = 1; i <= len; i++) {
int a = info[i - 1][0];
int b = info[i - 1][1];
for (int j = 0; j < m; j++) {
if (dp[i - 1][j] == maxValue)
continue;
int nextA = dp[i - 1][j] + a;
if (nextA < n) {
dp[i][j] = Math.min(nextA, dp[i][j]);
}
int nextB = j + b;
if (nextB < m) {
dp[i][nextB] = Math.min(dp[i][nextB], dp[i - 1][j]);
}
}
}
// System.out.println();
// for (int i = 0; i <= len; i++) {
// for (int j = 0; j < m; j++) {
// System.out.print(dp[i][j] + " ");
// }
// System.out.println();
// }
int answer = maxValue;
for (int j = 0; j < m; j++) {
answer = Math.min(answer, dp[len][j]);
}
return answer == maxValue ? -1 : answer;
}
}