Given an array A of non-negative integers, you are initially positioned at index 0 of the array.A[i] means the maximum jump distance from index i (you can only jump towards the end of the array).Determine the minimum number of jumps you need to reach the end of array. If you can not reach the end of the array, return -1.

Assumptions

  • The given array is not null and has length of at least 1.

Examples

  • {3, 3, 1, 0, 4}, the minimum jumps needed is 2 (jump to index 1 then to the end of array)

  • {2, 1, 1, 0, 2}, you are not able to reach the end of array, return -1 in this case.

  public int minJump(int[] array) {
    int[] dp = new int[array.length];
    for (int i = 1; i < array.length; i++) {
      dp[i] = Integer.MAX_VALUE;
      for (int j = 0; j < i; j++) {
        if (dp[j] != Integer.MAX_VALUE && array[j] >= i - j) {
          dp[i] = Math.min(dp[i], dp[j] + 1);
        }
      }
    }
    if(dp[dp.length - 1] == Integer.MAX_VALUE) {
      return -1;
    }
    return dp[dp.length - 1];
  }

follow up: 要跳出array,则只需多建一格,dp = new int[dp.length +1]

results matching ""

    No results matching ""