[LC]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.

二、我的思路

看成实际上求的是数组中后面的数和前面的数字的最大正差值。

我先把数组里的绝对数值转化为前后数字的差值,比如[7,1,5,3,6,4]转换为[0,-6,4,-2,3,-2]。

于是,求后面数字和前面数字的最大差值就变成了求差值数组的子数组最大和问题。


关于求最大和的方法,可以用n^3方法遍历:固定子数组起点、终点,再用一层循环算和。

也可以用动态规划的O(n)方法,参考了https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.04.md

该方法思路:

  • 用一个变量curSum记录当前状态下正在延续的最大子数组和,一个maxSum,为目前出现的所有数组的最大子数组和。
  • 对于当前要处理的新元素,要么加入当前正在延续的子数组;要么结束当前延续的子数组,并以该元素作为新数组的起始元素。
  • 如果当前元素加入延续子数组产生的和比该元素大的话,则把该元素加到延续数组;否则以该元素作为新数组起始元素。更新curSum。如果curSum > maxSum,则maxSum = curSum。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }
        
        for(int i = prices.length-1; i > 0; i --){
            prices[i] = prices[i] - prices[i-1];
        }
        prices[0] = 0;
        
        int currSum = 0;
	    int maxSum = prices[0];    

	    for (int j = 0; j < prices.length; j++)
	    {
		    currSum = (prices[j] > currSum + prices[j]) ? prices[j] : currSum + prices[j];
		    maxSum = (maxSum > currSum) ? maxSum : currSum;

	    }
        
	    return Math.max(maxSum, 0);
    }
}

三、淫奇技巧

1. 最高票答案和我想法一样,但是实现更为简单。直接用的差值,没有先把数组改变一下。

  public int maxProfit(int[] prices) {
        int maxCur = 0, maxSoFar = 0;
        for(int i = 1; i < prices.length; i++) {
            maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
            maxSoFar = Math.max(maxCur, maxSoFar);
        }
        return maxSoFar;
    }

*maxCur = current maximum value

*maxSoFar = maximum value found so far

2. 排名第二的答案是记录当前出现的最小值,然后记录至今为止出现的最大差值。

minPrice is the minimum price from day 0 to day i. And maxPro is the maximum profit we can get from day 0 to day i.

How to get maxPro? Just get the larger one between current maxPro and prices[i] - minPrice.

int maxProfit(vector<int> &prices) {
    int maxPro = 0;
    int minPrice = INT_MAX;
    for(int i = 0; i < prices.size(); i++){
        minPrice = min(minPrice, prices[i]);
        maxPro = max(maxPro, prices[i] - minPrice);
    }
    return maxPro;
}

四、知识点

主要还是需要多学习一些基本算法作为工具。否则就空有思路,无法更好的实现了。。继续加油!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值