买卖股票的最佳时机系列

买卖股票的最佳时机

题目来源:LeetCode 121.买卖股票的最佳时机
在这里插入图片描述

思路

这里题目要求最多只允许完成一笔交易。属于一道简单题,暴力法很容易想到,但是其实遍历一遍就可以了,设置一个最小值,遍历的时候不断更新最小值,用当前价格减去最小值即可得到当前天卖出股票的收益,取最大的收益即可。

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int res = 0;
        for (int i = 0; i < prices.length; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            res = Math.max(res, prices[i]-minPrice);
        }
        return res;
    }
}

买卖股票的最佳时机2

题目来源:LeetCode 122.买卖股票的最佳时机 II
在这里插入图片描述

思路

这道题是一个变形,买卖股票的次数从题目一的一次变为了无数次。这还是一道简单题。思路也比较简单,只需要找出所有非严格递增段,最大值减去最小值即为这一段的最大收益,每段的收益相加即可。

class Solution {
    public int maxProfit(int[] prices) {
        int minIndex = 0;
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < prices[i-1]) {
                res += prices[i-1]-prices[minIndex];
                minIndex = i;
            }
        }
        if (minIndex != prices.length-1) {
            res += prices[prices.length-1]-prices[minIndex];
        }
        return res;
    }
}

买卖股票的最佳时机3

题目来源:LeetCode 123.买卖股票的最佳时机 III
在这里插入图片描述

思路

之前做东方财富的笔试遇到过这道题。
这道题也是一个变形,买卖股票的次数变成了最多可以完成两笔交易。这道题就变成了一道困难题。

class Solution {
    public int maxProfit(int[] prices) {
        int buy1 = Integer.MAX_VALUE;
        int buy2 = Integer.MAX_VALUE;
        int pro1 = 0;
        int pro2 = 0;

        for (int i = 0; i < prices.length; i++) {
            buy1 = Math.min(buy1, prices[i]);
            pro1 = Math.max(pro1, prices[i]-buy1);

            buy2 = Math.min(buy2, prices[i]-pro1);
            pro2 = Math.max(pro2, prices[i]-buy2);
        }
        return pro2;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值