Minimize the Difference Between Target and Chosen Elements

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 the absolute value of a - b.

Example 1
1 2 3
4 5 6
7 8 9
Inputmat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
Output0
Choosing 1 from the first row, 5 from the second row, and 7 from the third row gives a sum of 13, which equals the target, so the absolute difference is 0.
Example 2
1
2
3
Inputmat = [[1],[2],[3]], target = 100
Output94
Choosing 1, 2, and 3 gives a sum of 6, and the absolute difference from 100 is 94.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 70
  • 1 <= mat[i][j] <= 70
  • 1 <= target <= 800

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate