给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
It is not a greedy algorithm and can be solved by dynamic programming. dp[i] indicates the maximum sum of the subarrays ending with A[i].
public class Solution {
public static void main(String[] args) {
int[] a = {-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubArray(a));
}
public static int maxSubArray(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int[] dp = new int[A.length];
dp[0] = A[0];
for (int i = 1; i < A.length; i++) {
if (dp[i-1] > 0) {
dp[i] = dp[i-1] + A[i];
} else {
dp[i] = A[i];
}
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < A.length; i++) {
max = max < dp[i] ? dp[i] : max;
}
return max;
}
}