diff --git a/interview_prep/algorithm/java/src/main/java/hoa/can/code/gg/Jumping.java b/interview_prep/algorithm/java/src/main/java/hoa/can/code/gg/Jumping.java new file mode 100644 index 00000000..340090f2 --- /dev/null +++ b/interview_prep/algorithm/java/src/main/java/hoa/can/code/gg/Jumping.java @@ -0,0 +1,29 @@ +package hoa.can.code.gg; + +import java.util.Arrays; + +/** + * https://leetcode.com/problems/jump-game/ + */ +public class Jumping { + final static int NO_WAY = Integer.MAX_VALUE; + public static boolean canJump(int[] nums) { + int[] memo = new int[nums.length]; + Arrays.fill(memo, -1); + return (minJumps(nums, 0, nums.length - 1, memo) > -1); + } + private static int minJumps(int steps[], int begin, int dest, int[] memo) { + if (begin == dest) + return 0; + if (steps[begin] == 0) + return NO_WAY; + + int minJump = NO_WAY; + for (int step = steps[begin]; step >= 1; --step) { + if (begin + step <= dest) { + minJump = Math.min(minJump, 1 + minJumps(steps, begin + step, dest, memo)); + } + } + return memo[begin] = minJump; + } +} diff --git a/interview_prep/algorithm/java/src/test/java/hoa/can/code/JumpingTest.java b/interview_prep/algorithm/java/src/test/java/hoa/can/code/JumpingTest.java new file mode 100644 index 00000000..ff7c578d --- /dev/null +++ b/interview_prep/algorithm/java/src/test/java/hoa/can/code/JumpingTest.java @@ -0,0 +1,23 @@ +package hoa.can.code; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static hoa.can.code.gg.Jumping.canJump; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class JumpingTest { + @Test + @DisplayName("ok") + public void yes() { + assertEquals(true, canJump(new int[]{2, 3, 1, 1, 4})); + assertEquals(true, canJump(new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9})); + } + + @Test + @DisplayName("nope") + public void no() { + assertEquals(true, canJump(new int[]{0})); + assertEquals(true, canJump(new int[]{0,1})); + } +}