LeetCode -- 121. Best Time to Buy and Sell Stock

来源:互联网 发布:java mvc web项目实例 编辑:程序博客网 时间:2024/05/18 16:39

题目:

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.


思路:

滴滴牛客网视频面试的时候正好让写这道题,可惜我当时没刷LeetCode,先写了个暴力,然后又写了一个dp的,还好最后面试官还算满意~

d[i]为到第i天为止的最大利润,d[0]=0,则有:

d[i]={0,prices[i]min,prices[i]<prices[i1]prices[i]<min;otherwise;


C++代码如下:

class Solution {public:    int maxProfit(vector<int>& prices) {        int max = 0, index = 0, len = prices.size();        if(len == 0)            return 0;        vector<int> d(len,0);        d[0] = 0;        for(int i=1;i<len;i++)        {            if(prices[i]<prices[i-1] && prices[i] < prices[index])            {                index = i;                d[i] = 0;            }            else            {                d[i] = prices[i] - prices[index];            }        }        for(int i=0;i<len;i++)        {            if(d[i]>max)                max = d[i];        }        return max;    }};
原创粉丝点击