Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Last active June 3, 2020 01:04
Show Gist options
  • Save germanescobar/7867fdaeef976372330995de502a8c4c to your computer and use it in GitHub Desktop.
Save germanescobar/7867fdaeef976372330995de502a8c4c to your computer and use it in GitHub Desktop.
var stoneGameII = function(piles) {
return stoneGameRec(piles, 1, [])
};
function stoneGameRec(piles, M, memo) {
if (piles.length === 0) return 0
if (piles.length === 1) return piles[0]
if (piles.length === 2) return piles[0] + piles[1]
const totalStones = piles.reduce((sum, e) => sum + e, 0)
let stones = 0
for (let i=1; i <= 2 * M; i++) {
const result = stoneGameRec(piles.slice(i), Math.max(i, M), memo)
if (totalStones - result > stones) {
stones = totalStones - result
}
}
return stones
}
var stoneGameII = function(piles) {
return stoneGameRec(piles, 0, 1, [])
};
function stoneGameRec(piles, index, M, memo) {
if (index === piles.length) return 0
if (index === piles.length - 1) return piles[index]
if (index === piles.length - 2) return piles[index] + piles[index+1]
if (memo[index]) return memo[index]
let totalStones = 0
for (let i=index; i < piles.length; i++) {
totalStones += piles[i]
}
let stones = 0
for (let i=index; i <= index + 2 * M; i++) {
const result = stoneGameRec(piles, i+1, Math.max(i, M), memo)
if (totalStones - result > stones) {
stones = totalStones - result
}
}
memo[index] = stones
return stones
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment