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
Minimize the Difference Between Target and Chosen Elements123Row 0 (chosen)456Row 1 (chosen)Target = 7Must choose one from each rowSum = 2 + 5 = 7Difference = |7 - 7| = 0Optimal Choice: Select elements that sum closest to targetTry all combinations: (1,4)=5, (1,5)=6, (1,6)=7, (2,4)=6, (2,5)=7, (2,6)=8, (3,4)=7, (3,5)=8, (3,6)=9Best sum is 7 (exact match), so minimum difference is 0
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
32.0K Views
Medium Frequency
~25 min Avg. Time
892 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