Skip to content

Commit 1961f04

Browse files
committed
Add solution #1000
1 parent 0612557 commit 1961f04

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,078 LeetCode solutions in JavaScript
1+
# 1,079 LeetCode solutions in JavaScript
22

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

@@ -808,6 +808,7 @@
808808
997|[Find the Town Judge](./solutions/0997-find-the-town-judge.js)|Easy|
809809
998|[Maximum Binary Tree II](./solutions/0998-maximum-binary-tree-ii.js)|Medium|
810810
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|
811812
1002|[Find Common Characters](./solutions/1002-find-common-characters.js)|Easy|
812813
1004|[Max Consecutive Ones III](./solutions/1004-max-consecutive-ones-iii.js)|Medium|
813814
1005|[Maximize Sum Of Array After K Negations](./solutions/1005-maximize-sum-of-array-after-k-negations.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
};

0 commit comments

Comments
 (0)