贪心:
p[2] - p[0]
= p[2] - p[1]
+ p[1] - p[0]
class Solution {
public int maxProfit(int[] prices) {
int[] sub = new int[prices.length-1];
int index = 0;
int res = 0;
for(int i = 1 ; i < prices.length;i++){
sub[index++] = prices[i] - prices[i-1];
}
for(int i = 0 ; i < sub.length;i++){
if(sub[i]>0){
res+=sub[i];
}
}
return res;
}
}
贪心
int cover
变量,代表数组的覆盖范围cover = cover + nums[i]
,同时覆盖范围取 范围内最大值cover
范围内的数组,每次根据 当前数组的 nums
值,取当前范围最大的可到达数 为当前 cover
值
cover
超出 数组长度 直接返回 true
false
class Solution {
public boolean canJump(int[] nums) {
int cover = 0;
for(int i = 0 ; i<=cover ;i++){
cover = Math.max(i+nums[i],cover);
if(cover >= nums.length-1){
return true;
}
}
return false;
}
}
贪心
cover
,区别于跳跃游戏基础版的点在于,再定义一个 nextCover
,记录每次遍历到的最大范围,但每次不一定更新 cover
cover
走不下去时候,再更新 cover
,对结果进行 ++class Solution {
public int jump(int[] nums) {
int cover = 0;
int nextCover = 0;
int res = 0;
for(int i = 0 ; i < nums.length;i++){
nextCover = Math.max(nums[i]+i,nextCover);
if(i==cover){
if(cover!=nums.length-1){
res++;
cover = nextCover;
}
}
}
return res;
}
}