Minimize the Difference Between Target and Chosen Elements - Problem
You are given an m x n integer matrix mat and an integer target.
Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
The absolute difference between two numbers a and b is |a - b|.
Input & Output
Example 1 — Perfect Match
$
Input:
mat = [[1,2,3],[4,5,6]], target = 7
›
Output:
1
💡 Note:
Choose 1 from first row and 6 from second row: 1 + 6 = 7, but we can get closer with 2 + 5 = 7. Actually, the minimum difference is |7 - 6| = 1 when choosing 1 + 5 = 6.
Example 2 — Exact Target
$
Input:
mat = [[1,2],[3,4]], target = 4
›
Output:
0
💡 Note:
Choose 1 from first row and 3 from second row: 1 + 3 = 4, which exactly equals target. Difference is |4 - 4| = 0.
Example 3 — Single Row
$
Input:
mat = [[1,2,9,8,7]], target = 6
›
Output:
1
💡 Note:
With only one row, we must choose one element. The closest to 6 is 7, giving difference |6 - 7| = 1.
Constraints
- m == mat.length
- n == mat[i].length
- 1 ≤ m, n ≤ 70
- 1 ≤ mat[i][j] ≤ 70
- 1 ≤ target ≤ 800
Visualization
Tap to expand
Understanding the Visualization
1
Input
Matrix with rows and target value
2
Process
Select one element from each row
3
Output
Minimum absolute difference from target
Key Takeaway
🎯 Key Insight: Use dynamic programming to track all possible sums efficiently instead of trying every combination
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code