leetcode-121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output:5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.

. 解法一:

利用 寻找最大子数列-Kadane算法
建议不理解该算法的可以先看一下上面的连接里的介绍。

以下解法就是在kadane算法的基础上,将求和转化为求最大的差
对于[7, 1, 5, 3, 6, 4] 来说的例子:
求最大差值的方法

  • 其中用 两个元素间的 每相邻两个元素的差 的和 表示这两个元素的差

  • 当元素之间的差的和小于0时,就可以 重新开始计算了,因为后面的累加 (两个元素之间的差)加不加0是无所谓的。

  • 出现prices[i+1]-prices[i]<0 的情况是可以的,因为max的值不会受影响,而对于后面更大的数字,这两个元素之间的差也是要累加进来用于计算 前面的元素和后面元素的差

  • 遍历过程中,要用一个变量(max)记录到当前元素为止所获得过的最大值

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0 || prices.length == 1) return 0;
        int mCur=0,max=0;
        int re = prices[1]-prices[0];
        for (int i = 0; i < prices.length-1; i++) {
            mCur = Math.max(0,mCur+=prices[i+1]-prices[i]);
            max = Math.max(max,mCur);
        }
        return max;
    }
}

. 解法二:

由上面的图我们可以知道,最终结果是最较小值和之后的最大值的差

我们可以再遍历过程中,每当找一个 较小值 时就计算 它 和 后面 每一个元素之间的差值,并保存,用 maxprofit 保存求过的最大的差值。

这种方法下,即使出现后面的元素更小,但是该元素和后面的元素的差并不是最大的时也是不影响结果的,因为maxprofit会保存之前求过的较大的值

public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice)
                minprice = prices[i];
            else if (prices[i] - minprice > maxprofit)
                maxprofit = prices[i] - minprice;
        }
        return maxprofit;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值