[Leetcode] 121. Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝联盟怎么看隐藏券 编辑:程序博客网 时间:2024/06/07 14:42

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]

原创粉丝点击