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
Minimize Difference Between Target and Chosen Elements INPUT Matrix (mat) 1 2 3 Row 0 4 5 6 Row 1 Target 7 Input Values: mat = [[1,2,3],[4,5,6]] target = 7 Choose 1 element per row ALGORITHM STEPS 1 Initialize DP Set Start with {0} for possible sums 2 Process Row 0 Add 1,2,3 to each sum Sums: {1, 2, 3} 3 Process Row 1 Add 4,5,6 to each sum Sums: {5,6,7,8,9} 4 Find Min Difference |target - sum| for each Possible Sums Table: 1+4=5 |7-5|=2 1+5=6 |7-6|=1 2+5=7 |7-7|=0 or 1+6=7 2+6=8 |7-8|=1 3+6=9 |7-9|=2 Best: choose 1 and 6 (sum=7) FINAL RESULT Optimal Selection 1 2 3 Row 0 4 5 6 Row 1 Calculation: 1 + 6 = 7 |7 - 7| = 0 OUTPUT 0 OK - Minimum difference found! Sum equals target exactly Key Insight: Use Dynamic Programming with a Set to track all possible sums. For each row, compute new sums by adding each element to existing sums. Time: O(m * n * maxSum), Space: O(maxSum). This avoids exponential enumeration by reusing computed states. Pruning sums far from target improves performance. TutorialsPoint - Minimize the Difference Between Target and Chosen Elements | Optimal Solution
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