Minimize the Difference Between Target and Chosen Elements - Problem
You are given an m ร n integer matrix and an integer target. Your mission is to select exactly one integer from each row to create a subset whose sum is as close as possible to the target value.
Goal: Minimize the absolute difference between the target and the sum of your chosen elements.
Input: A 2D matrix mat and an integer target
Output: The minimum possible absolute difference
Example: Given matrix [[1,2,3],[4,5,6],[7,8,9]] and target 13, you could choose [1,5,7] with sum 13, giving difference |13-13| = 0.
Input & Output
example_1.py โ Basic Case
$
Input:
mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
โบ
Output:
0
๐ก Note:
We can choose [1,5,7] with sum 13, giving difference |13-13| = 0. This is optimal since we can achieve the exact target.
example_2.py โ Impossible Exact Match
$
Input:
mat = [[1],[2],[3]], target = 100
โบ
Output:
94
๐ก Note:
We must choose [1,2,3] giving sum 6. The difference is |6-100| = 94. No other combination is possible.
example_3.py โ Multiple Options
$
Input:
mat = [[1,2,9,8,7]], target = 6
โบ
Output:
1
๐ก Note:
With only one row, we can choose any single element. Element 7 gives difference |7-6| = 1, which is closest to target 6.
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
Store 1: Electronics
Choose from $1, $2, or $3 items. All are possible starting points.
2
Store 2: Clothing
Add $4, $5, or $6 to each previous total. Now we can spend $5-$9.
3
Store 3: Books
Add $7, $8, or $9 to each total. Final possible totals: $12-$18.
4
Find Best Match
Target is $13. Closest achievable total is $12, difference = $1.
Key Takeaway
๐ฏ Key Insight: Dynamic Programming transforms an exponential search into efficient sum tracking. We build possible sums incrementally rather than exploring all combinations, achieving polynomial time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code