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
๐Ÿ›’ Shopping Cart OptimizationGoal: Spend as close to $13 as possibleElectronics$1 $2 $3Possible: $1,$2,$3Clothing$4 $5 $6Possible: $5-$9Books$7 $8 $9Possible: $12-$18๐ŸŽฏ Target: $13Closest: $12Difference: $1Dynamic Programming ProcessStep 1: Start with {$0}Step 2: Add electronics โ†’ {$1, $2, $3}Step 3: Add clothing โ†’ {$5, $6, $7, $8, $9}Step 4: Add books โ†’ {$12, $13, $14, $15, $16, $17, $18}โšก Key InsightInstead of trying 3ยณ = 27 combinations, we track possible sums efficiently!
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.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
43.6K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen