122. 买卖股票的最佳时机 II
贪心算法
也可以用动态规划
贪心算法的做法:
从前向后遍历,当当前价格低于手中持有的股票价格时,就将手中持有的股票变为当前股票
当遇见当前价格高于手中的股票价格时,就卖出股票,结算收益,同时手中再持有当前股票
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int curPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] > curPrice) {
maxProfit += prices[i] - curPrice;
}
curPrice = prices[i];
}
return maxProfit;
}
}
——————————————————————————————————————————
55. 跳跃游戏
贪心算法
每一步都尽量跳到下一步能跳的更远的位置
class Solution {
public boolean canJump(int[] nums) {
int curIndex = 0;
while(curIndex < nums.length - 1){
int nextStep = nums[curIndex];
if(nextStep == 0){
return false;
}
int maxCurIndex = curIndex + nextStep;
for(int i = curIndex + 1; i < nums.length && i <= maxCurIndex; i++){
curIndex = i;
if(i + nums[i] > maxCurIndex){
break;
}
}
}
return true;
}
}
——————————————————————————————————————————
45. 跳跃游戏 II
贪心算法
和55.跳跃游戏做对比
55题中,在向前跳的过程中,找到了覆盖范围更远的位置,就跳到这个位置继续向前
在本题中,我们可能需要遍历当前位置能跳到的所有位置,从中找到覆盖范围最大的位置,跳到这个位置继续向下遍历
class Solution {
public int jump(int[] nums) {
int minStep = 0;
int curIndex = 0;
while(curIndex < nums.length - 1) {
minStep++;
int curIndexStepLen = nums[curIndex];
int nexIndex = curIndex + curIndexStepLen;
if (nexIndex >= nums.length - 1) {
break;
}
for (int i = curIndex + 1; i < nums.length && i <= curIndex + curIndexStepLen; i++) {
if (i + nums[i] > nexIndex + nums[nexIndex]){
nexIndex = i;
}
}
curIndex = nexIndex;
}
return minStep;
}
}