Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 88c86e9

Browse files
committed
Add solution #1981
1 parent b47b95d commit 88c86e9

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,667 LeetCode solutions in JavaScript
1+
# 1,668 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1520,6 +1520,7 @@
15201520
1977|[Number of Ways to Separate Numbers](./solutions/1977-number-of-ways-to-separate-numbers.js)|Hard|
15211521
1979|[Find Greatest Common Divisor of Array](./solutions/1979-find-greatest-common-divisor-of-array.js)|Easy|
15221522
1980|[Find Unique Binary String](./solutions/1980-find-unique-binary-string.js)|Medium|
1523+
1981|[Minimize the Difference Between Target and Chosen Elements](./solutions/1981-minimize-the-difference-between-target-and-chosen-elements.js)|Medium|
15231524
1985|[Find the Kth Largest Integer in the Array](./solutions/1985-find-the-kth-largest-integer-in-the-array.js)|Medium|
15241525
1996|[The Number of Weak Characters in the Game](./solutions/1996-the-number-of-weak-characters-in-the-game.js)|Medium|
15251526
2000|[Reverse Prefix of Word](./solutions/2000-reverse-prefix-of-word.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1981. Minimize the Difference Between Target and Chosen Elements
3+
* https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n integer matrix mat and an integer target.
7+
*
8+
* Choose one integer from each row in the matrix such that the absolute difference between
9+
* target and the sum of the chosen elements is minimized.
10+
*
11+
* Return the minimum absolute difference.
12+
*
13+
* The absolute difference between two numbers a and b is the absolute value of a - b.
14+
*/
15+
16+
/**
17+
* @param {number[][]} mat
18+
* @param {number} target
19+
* @return {number}
20+
*/
21+
var minimizeTheDifference = function(mat, target) {
22+
const m = mat.length;
23+
const maxSum = 70 * m;
24+
let possibleSums = new Set([0]);
25+
26+
for (const row of mat) {
27+
const nextSums = new Set();
28+
for (const num of row) {
29+
for (const sum of possibleSums) {
30+
const newSum = sum + num;
31+
if (newSum <= target + maxSum) {
32+
nextSums.add(newSum);
33+
}
34+
}
35+
}
36+
possibleSums = nextSums;
37+
}
38+
39+
let result = Infinity;
40+
for (const sum of possibleSums) {
41+
result = Math.min(result, Math.abs(sum - target));
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)