Skip to content

Commit 00bfcf2

Browse files
committed
Add solution #2033
1 parent 71facdf commit 00bfcf2

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,7 @@
896896
2016|[Maximum Difference Between Increasing Elements](./solutions/2016-maximum-difference-between-increasing-elements.js)|Easy|
897897
2017|[Grid Game](./solutions/2017-grid-game.js)|Medium|
898898
2027|[Minimum Moves to Convert String](./solutions/2027-minimum-moves-to-convert-string.js)|Easy|
899+
2033|[Minimum Operations to Make a Uni-Value Grid](./solutions/2033-minimum-operations-to-make-a-uni-value-grid.js)|Medium|
899900
2037|[Minimum Number of Moves to Seat Everyone](./solutions/2037-minimum-number-of-moves-to-seat-everyone.js)|Easy|
900901
2047|[Number of Valid Words in a Sentence](./solutions/2047-number-of-valid-words-in-a-sentence.js)|Easy|
901902
2053|[Kth Distinct String in an Array](./solutions/2053-kth-distinct-string-in-an-array.js)|Medium|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 2033. Minimum Operations to Make a Uni-Value Grid
3+
* https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/
4+
* Difficulty: Medium
5+
*
6+
* You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x
7+
* to or subtract x from any element in the grid.
8+
*
9+
* A uni-value grid is a grid where all the elements of it are equal.
10+
*
11+
* Return the minimum number of operations to make the grid uni-value. If it is not possible,
12+
* return -1.
13+
*/
14+
15+
/**
16+
* @param {number[][]} grid
17+
* @param {number} x
18+
* @return {number}
19+
*/
20+
var minOperations = function(grid, x) {
21+
if (values.length === 1) return 0;
22+
const values = grid.flat();
23+
values.sort((a, b) => a - b);
24+
const median = values[Math.floor(values.length / 2)];
25+
let operations = 0;
26+
27+
for (const value of values) {
28+
const diff = Math.abs(value - median);
29+
if (diff % x !== 0) return -1;
30+
operations += diff / x;
31+
}
32+
33+
return operations;
34+
};

0 commit comments

Comments
 (0)