File tree 2 files changed +52
-1
lines changed
2 files changed +52
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,078 LeetCode solutions in JavaScript
1
+ # 1,079 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcode.com/ ] ( https://leetcode.com/ )
4
4
808
808
997|[ Find the Town Judge] ( ./solutions/0997-find-the-town-judge.js ) |Easy|
809
809
998|[ Maximum Binary Tree II] ( ./solutions/0998-maximum-binary-tree-ii.js ) |Medium|
810
810
999|[ Available Captures for Rook] ( ./solutions/0999-available-captures-for-rook.js ) |Easy|
811
+ 1000|[ Minimum Cost to Merge Stones] ( ./solutions/1000-minimum-cost-to-merge-stones.js ) |Hard|
811
812
1002|[ Find Common Characters] ( ./solutions/1002-find-common-characters.js ) |Easy|
812
813
1004|[ Max Consecutive Ones III] ( ./solutions/1004-max-consecutive-ones-iii.js ) |Medium|
813
814
1005|[ Maximize Sum Of Array After K Negations] ( ./solutions/1005-maximize-sum-of-array-after-k-negations.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1000. Minimum Cost to Merge Stones
3
+ * https://leetcode.com/problems/minimum-cost-to-merge-stones/
4
+ * Difficulty: Hard
5
+ *
6
+ * There are n piles of stones arranged in a row. The ith pile has stones[i] stones.
7
+ *
8
+ * A move consists of merging exactly k consecutive piles into one pile, and the cost of
9
+ * this move is equal to the total number of stones in these k piles.
10
+ *
11
+ * Return the minimum cost to merge all piles of stones into one pile. If it is impossible,
12
+ * return -1.
13
+ */
14
+
15
+ /**
16
+ * @param {number[] } stones
17
+ * @param {number } k
18
+ * @return {number }
19
+ */
20
+ var mergeStones = function ( stones , k ) {
21
+ const n = stones . length ;
22
+ if ( ( n - 1 ) % ( k - 1 ) !== 0 ) return - 1 ;
23
+
24
+ const prefixSums = new Array ( n + 1 ) . fill ( 0 ) ;
25
+ for ( let i = 0 ; i < n ; i ++ ) {
26
+ prefixSums [ i + 1 ] = prefixSums [ i ] + stones [ i ] ;
27
+ }
28
+
29
+ const dp = new Array ( n ) . fill ( ) . map ( ( ) => new Array ( n ) . fill ( 0 ) ) ;
30
+
31
+ for ( let len = k ; len <= n ; len ++ ) {
32
+ for ( let start = 0 ; start + len <= n ; start ++ ) {
33
+ const end = start + len - 1 ;
34
+ dp [ start ] [ end ] = Infinity ;
35
+
36
+ for ( let mid = start ; mid < end ; mid += k - 1 ) {
37
+ dp [ start ] [ end ] = Math . min (
38
+ dp [ start ] [ end ] ,
39
+ dp [ start ] [ mid ] + dp [ mid + 1 ] [ end ]
40
+ ) ;
41
+ }
42
+
43
+ if ( ( len - 1 ) % ( k - 1 ) === 0 ) {
44
+ dp [ start ] [ end ] += prefixSums [ end + 1 ] - prefixSums [ start ] ;
45
+ }
46
+ }
47
+ }
48
+
49
+ return dp [ 0 ] [ n - 1 ] ;
50
+ } ;
You can’t perform that action at this time.
0 commit comments