[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 i-th 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. different = 6 - 1 = 5 (not 7 - 1 = 6, as selling price needs to be large 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.

给定一个数组,表示股票第i天的价格,怎么进行股票买卖才能获得最大的利润。注意,只能进行一次股票买卖。

例如:
给定数组[7, 1, 5, 3, 6, 4],则最大利润为6-1=5;
给定数组[7, 6, 4, 3, 1],则最大利润为0。

解题思路
这是一道比较简单的题目。可以有多种解法。

方法一:贪心算法
只需要通过一个简单的贪心算法便可以得到最大利润。
但是需要特别主要的是,股票买卖过程中要满足低进高出,也就是说,价格低的那一天必须在价格高的一天之前。

代码实现如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0)
            return 0;
        int profit = 0;     //差价,也就是利润
        int cur_min = prices[0];        //当前最小的股票价格

        for(int i = 1; i < prices.size(); i++)
        {
            profit = max(profit, prices[i] - cur_min);      //最大的利润
            cur_min = min(prices[i], cur_min);              //当前最小的股票价格
        }

        return profit;
    }
};

方法二:动态规划
设dp[i]是[0,1,2…i]区间的最大利润,则该问题的一维动态规划方程如下:
dp[i+1] = max{dp[i], prices[i+1] - minprices} ,minprices是区间[0,1,2…,i]内的最低价格。
要求解的最大利润 = max{dp[0], dp[1], dp[2], …, dp[n-1]}

代码实现如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int len = prices.size();
        if(len <= 1)return 0;
        int res = prices[1] - prices[0], minprice = prices[0];
        for(int i = 2; i < len; i++)
        {
            minprice = min(prices[i-1], minprice);
            if(res < prices[i] - minprice)
                res = prices[i] - minprice;
        }
        if(res < 0)return 0;
        else return res;
    }
};

这道题比较简单,限制了只能进行一次股票交易。,LeetCode第122道题,Best Time to Buy Sell Stock II跟本题很相似,但是[122]并不限制股票交易的次数。下一篇将重点介绍[122]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值