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:
0
💡 Note:
Choose 1 from first row and 6 from second row: 1 + 6 = 7, which exactly equals target. Difference is |7 - 7| = 0. Other combinations like 2 + 5 = 7 and 3 + 4 = 7 also give difference 0.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code