Skip to content

Commit

Permalink
solution: 0045. Jump Game II
Browse files Browse the repository at this point in the history
  • Loading branch information
flynnpark committed Jan 9, 2024
1 parent 44eab0b commit 2f727d4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/0045/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,16 @@ describe('0045. Jump Game II', () => {
},
output: 2,
},
{
input: {
nums: [1, 1, 1, 1, 1],
},
output: 4,
},
];

test.each(testCases)('Case %#', ({ input: { nums }, output }) => {
const relsult = jump(nums);
const result = jump(nums);
expect(result).toStrictEqual(output);
});
});
17 changes: 16 additions & 1 deletion src/0045/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
function jump(nums: number[]): number {}
function jump(nums: number[]): number {
let result = 0;
let availableSteps = 0;
let currentIndex = 0;
for (let i = 0; i < nums.length - 1; i++) {
if (nums.length - 1 <= i + nums[i]) {
return result + 1;
}
availableSteps = Math.max(availableSteps, nums[i] + i);
if (i === currentIndex) {
result += 1;
currentIndex = availableSteps;
}
}
return result;
}

export { jump };

0 comments on commit 2f727d4

Please sign in to comment.