File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
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
+
1
54
/**
2
55
* @param {number[] } nums
3
56
* @return {number }
You can’t perform that action at this time.
0 commit comments