Skip to content

Commit 97a9003

Browse files
authored
Update 2967-minimum-cost-to-make-array-equalindromic.js
1 parent 5d92637 commit 97a9003

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

2967-minimum-cost-to-make-array-equalindromic.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,56 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var minimumCost = function (nums) {
6+
nums.sort((a, b) => a - b)
7+
const n = nums.length
8+
const median = nums[Math.floor(n / 2)]
9+
10+
// Helper function to find the next palindromic number greater than or equal to x
11+
const getNextPalindromic = (x) => {
12+
while (true) {
13+
const strX = String(x)
14+
const revStrX = strX.split('').reverse().join('')
15+
if (strX === revStrX) return x
16+
x++
17+
}
18+
}
19+
20+
// Helper function to find the previous palindromic number smaller than or equal to x
21+
const getPrevPalindromic = (x) => {
22+
while (true) {
23+
const strX = String(x)
24+
const revStrX = strX.split('').reverse().join('')
25+
if (strX === revStrX) return x
26+
x--
27+
}
28+
}
29+
30+
const candidate1 = getNextPalindromic(median)
31+
const candidate2 = getPrevPalindromic(median)
32+
33+
let cost1 = 0
34+
let cost2 = 0
35+
36+
// Calculate the cost for candidate1
37+
for (const num of nums) {
38+
cost1 += Math.abs(num - candidate1)
39+
}
40+
41+
// Calculate the cost for candidate2
42+
for (const num of nums) {
43+
cost2 += Math.abs(num - candidate2)
44+
}
45+
46+
// Return the minimum cost between candidate1 and candidate2
47+
return Math.min(cost1, cost2)
48+
}
49+
50+
// another
51+
52+
53+
154
/**
255
* @param {number[]} nums
356
* @return {number}

0 commit comments

Comments
 (0)