Skip to content

Commit

Permalink
leetcode(45-jump-game-ii): working solution
Browse files Browse the repository at this point in the history
  • Loading branch information
uldissturms committed Sep 24, 2019
1 parent ca650b3 commit e7f94f9
Showing 1 changed file with 58 additions and 3 deletions.
61 changes: 58 additions & 3 deletions leetcode/45-jump-game-ii.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ test('solves jump list', t => {

test('solves jump list - with zero as value', t => {
t.is(solve([2, 3, 1, 0, 4]), 2)
t.is(solve([1, 2, 0, 1]), 2) // 60th test case
})

test('solves jump list - empty list', t => {
Expand All @@ -25,27 +26,81 @@ test('solves jump list - two items', t => {
t.is(solve([2, 1]), 1)
})

test('multiple ones', t => {
t.is(solve([1, 2, 1, 1, 1]), 3) // 65th test case
})

test('solves jump list - large list', t => {
const size = 50000
t.is(solve(new Array(size).fill(1)), size - 1)
})

test.skip('solves jump list - large descending list', t => {
test('solves jump list - large descending list', t => {
const size = 25000
const input = new Array(size).fill(1).map((_, idx) => size - idx)
t.is(solve(input), 1)
})

test.skip('solves jump list - large descending list twice', t => {
test('solves jump list - large descending list twice', t => {
const size = 25000
const list = new Array(size).fill(1).map((_, idx) => size - idx)
t.is(solve(list.concat(list)), 2)
})

test('solves jump list - value greater than prev', t => {
t.is(solve([4, 3, 1]), 1)
t.is(solve([4, 1, 3, 1]), 1)
})

test('solves jump list - value less than prev', t => {
t.is(solve([2, 4, 2]), 1)
t.is(solve([4, 5, 2, 4, 2]), 1)
})

const solve = (jumps) =>
solveI(jumps)
solveI2(jumps)
// solveI(jumps)
// solveR(jumps)[0]

const solveI2 = (jumps) => {
const len = jumps.length
if (len <= 1) {
return 0
}

const map = new Array(jumps.length).fill(0).map((_, idx) => ([Infinity, idx]))
map[len - 1] = [0, 0]

for (let idx = len - 2; idx >= 0; idx--) {
const curJumps = jumps[idx]

// deadend - leave as infinity
if (curJumps === 0) {
map[idx] = [Infinity, 0]
continue
}

const [prevC, prevUsed] = map[idx + 1]
let [bestC, bestUsed] = [prevC + 1, 1] // zero case to be handled later
const diff = curJumps - prevUsed
const prevEnd = idx + prevUsed + 1

if (diff > 0) {
for (let pos = prevEnd; pos < Math.min(prevEnd + diff, len); pos++) {
const [candidateC] = map[pos]
if (candidateC + 1 < bestC) {
bestC = candidateC + 1
bestUsed = pos - idx
}
}
}

map[idx] = [bestC, bestUsed]
}

return map[0][0]
}

const solveI = (jumps) => {
const len = jumps.length
if (len <= 1) {
Expand Down

0 comments on commit e7f94f9

Please sign in to comment.