Minimize the Difference Between Target and Chosen Elements LeetCode solution in Java

1
class Solution {
2
public int minimizeTheDifference(int[][] mat, int target) {
3
Integer[][] dp = new Integer[mat.length][5001];
4
return minDiff(mat, 0, target, 0, dp);
5
}
6

7
public int minDiff(int[][] mat, int index, int target, int val, Integer[][] dp) {
8
if (index == mat.length) {
9
return Math.abs(val - target);
10
}
11
if (dp[index][val] != null) {
12
return dp[index][val];
13
}
14

15
int res = Integer.MAX_VALUE;
16
for (int i = 0; i < mat[0].length; i++) {
17
res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));
18
}
19

20
return dp[index][val] = res;
21
}
22
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0