第十一周题解

45. 跳跃游戏Ⅱ

解法一:

class Solution {
    public int jump(int[] nums) {
        int max = 0; //下一次能跳到的最远距离
        int step = 0; //记录跳跃次数
        int next = 0;  //上一次能跳到的最远距离,即边界,如果预测的时候到达这个位置,步数就要+1
        //从原点开始跳,预测目前站的地方能跳到的最远范围内的每一个位置,跳到下一次能跳到更远地方的位置,开始下一次预测
        for(int i = 0; i < nums.length-1; i ++){
        //因为是起跳的时候就+1了,如果最后一次跳跃刚好到达了最后一个位置,那么遍历到最后一个位置的时候就会再次起跳,因此不能遍历最后一个位置
            max = max > nums[i]+i ? max : nums[i]+i;
            if(i == next){
                //预测到达了边界,这时候跳到此时max最大的地方,开始下一次起跳,更新边界,开始下一次预测
                next = max;
                step ++;
            }
        }
        return step;
    }
}

解法二:

class Solution {
    public int jump(int[] nums) {
        //从最后一个位置往前查找,找到能跳到当前位置的下标最小的地方,即离当前位置最远的地方
        int now = nums.length - 1;
        int step = 0; //记录步数
        while(now > 0){
        //从左到右遍历,找到的第一个可以到达当前位置的地方就是最远的地方
            for(int i = 0; i < now; i ++){
                if(nums[i]+i >= now){
                    now = i;
                    step ++;
                    break;
                }
            }
        }
        return step;
    }
}

122. 买卖股票的最佳时机Ⅱ

解法一:

class Solution {
    public int maxProfit(int[] prices) {
    	//如果给的天数小于2,就不用买卖了
    	if(prices.length < 2){
			return 0;
		}
        int max = 0;
        //遍历每一天,如果第二天的价格比今天的价格高那么就今天买明天卖,差价就是赚的钱
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1])
                max += prices[i] - prices[i - 1];
        }
        return max;
    }
}

解法二:

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }

        int[] cash = new int[prices.length]; //保证利润最大时手里的钱
        int[] hold = new int[prices.length]; //每天买了股票后手里的钱,即总财产为手里的钱和当天的股票价之和
        cash[0] = 0; //第一天没有买股票,持有0
        hold[0] = -prices[0]; //第一天买了股票,持有-prices[0]
        
        for (int i = 1; i < prices.length; i++) {
            //比较前一天没买股票和前一天买了股票今天卖出的收益高低,选择高的
            cash[i] = Math.max(cash[i - 1], hold[i - 1] + prices[i]);
            //比较前一天买股票还是今天买股票手里剩的钱的多少,选择多的
            hold[i] = Math.max(hold[i - 1], cash[i - 1] - prices[i]);
        }
        return cash[prices.length - 1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值