Best Time to Buy and Sell Stock

leetcode中的股票问题(1)

最近股市比较吸引眼球,而正好刷到了leetcode中股票问题,啥都不说了,我们来一起探讨探讨。
https://leetcode.com/problems/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.
翻译:有一个int类型数组,第 i 个元素表示股票在这一天的价格,如果最多只允许你进行一手交易(在某天买入股票然后在之后的某一天卖掉股票),设计一种算法找出最大的收益。

问题分析

先来张图直观的理解一下:
股价趋势图
凭直觉,不难发现我们要找的其实是:
这里写图片描述
这一手交易可以赚9-2 =7元钱,直观的感受当然是拿最高的票价减去最低的票价。但是可以看出,12号的票价是最低的,为1元,但是却没有用,因为虽然可以以1元的价格买入,但其后并没有很高的价格可以卖出了,很可惜~
也就是说,高价出现在低价后面才有意义,说白了无非是要找两个数值:买入的那一天(buy),和卖出的那一天 (sell) ,返回值为 maxpricesellprice(buy) price(x) 表示股票在第x天的价格。
假设我们分析在第i天卖出所能获得的最大收益,则必然是 price(i)min(i)>0?price(i)min(i):0 这里我们约定 min(i) 表示第i天之前的最低价,当然如果第i天之前最小的股价都比第i天大,那在这一天卖出只能亏钱咯,而题目中说at most one transaction所以买卖不做咯。
然后的想法就简单啦,我们从做到右扫一遍,记录在每天卖出的最大收益,用一个标记来维护最大值就行啦~~~

代码

public int maxProfit(int[] prices) {
    //less then two days, no game
    if(prices.length < 2)
    {
        return 0;
    }

    //tag to maintian the min price
    int leastTag = prices[0];
    //tag to maintian the max profit
    int profit = 0;
    for(int i = 1; i < prices.length; i++)
    {
        if( prices[i] - leastTag > profit)
        {
            profit = prices[i] - leastTag;
        }
        //else means price[i] < profit + leastTag
        //but not necessarily price[i] < leastTag
        else if(prices[i] < leastTag) 
        {
            leastTag = prices[i];
        }
    }
    return profit;
}

今天就到这里咯,明天来玩股票的2、3、4题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值