Dynamic Programming usually applies to 1-dimensional problem and looking for max or min problem.
Similar Problems:
- Longest Ascending SubArray
- Longest Ascending SubSequence
- Cutting rope
- Array Hopper
- Word Break
Problems Description:
Longest Ascending SubArray
Given an unsorted array, find the length of the longest subarray in which the numbers are in ascending order.
Assumptions
The given array is not null
Examples
{7, 2, 3, 1, 5, 8, 9, 6}, longest ascending subarray is {1, 5, 8, 9}, length is 4.
{1, 2, 3, 3, 4, 4, 5}, longest ascending subarray is {1, 2, 3}, length is 3.
Problem Analysis(Induction Rule):
dp[i] = 1: array[i] <= array[i - 1]
dp[i] = dp[i - 1] + 1: array[i] > array[i - 1]
Longest Ascending Subsequence
Given an array A[0]...A[n-1] of integers, find out the length of the longest ascending subsequence.
Assumptions
A is not null
Examples
Input: A = {5, 2, 6, 3, 4, 7, 5}
Output: 4
Because [2, 3, 4, 5] is the longest ascending subsequence.
Problem Analysis(Induction Rule):
dp[i] represents the longest ascending subsequence ending at index i
Array Hopper
I.
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 that position (you can only jump towards the end of the array). Determine if you are able to reach the last index.
Assumptions
The given array is not null and has length of at least 1.
Examples
{1, 3, 2, 0, 3}, we are able to reach the end of array(jump to index 1 then reach the end of the array)
{2, 1, 1, 0, 2}, we are not able to reach the end of array
Problem Analysis(Induction Rule):
dp[i] means from index 0, can jump to index i
Solution:
public boolean canJump(int[] array) {
//initialization
boolean[] dp = new boolean[array.length];
dp[0] = true;
for (int i = 1; i < array.length; i++) {for (int j = 0; j < i; j++) {if (dp[j] && j + array[j] >= i) {dp[i] = true;
break;
}
}
}
return dp[array.length - 1];
}
II.
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.
Solution:
public int minJump(int[] array) {int[] dp = new int[array.length];
dp[0] = 0;
for (int i = 1; i < array.length; i++) {dp[i] = -1;
for (int j = 0; j < i; j++) {if (j + array[j] >= i && dp[j] != -1) {if(dp[i] == -1 || dp[i] > dp[j] + 1) {dp[i] = dp[j] + 1;
}
}
}
}
return dp[array.length - 1];
}