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.

题目的大意是给定一个数组,数组的元素代表该天股票的价格,如果只能交易一次,让我们找出最大的利润。

这道题的算法是非常简单的,只需要把数组从头到尾扫一遍,用一个变量记录当前股票的最小值,假设我们是在当前股票取最小值时买入的,如果现在出售股票获得的利润比当前记录的利润高,则把这个利润更新为当前的利润,如果出现一个比当前记录的最小值还小的值,则更新最小值。

其实这个算法是一个动态规划的算法,公式为v[i]=max(v[i-1], prices[i]-min),但是这个数组可以用一个变量代替,所以我为了节省空间,只是存储了当前的利润最大值。

这个算法只有一个循环,所以复杂度是O(n),以下为源代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()==0) return 0;
        int minimum=prices[0],pro=0;
        for(int i=1;i<prices.size();i++) 
        {
        	if(prices[i]>minimum+pro) pro=prices[i]-minimum;
        	if(prices[i]<minimum) minimum=prices[i];
        }
        return pro;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值