LeetCode----best-time-to-buy-and-sell-stock

来源:互联网 发布:讲诚信知敬畏发言稿 编辑:程序博客网 时间:2024/06/09 19:36

题目描述


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.

------------------------------------------------------------------------------------------------------------
求解思路:
1,先找到第一个较小买入价格,然后找到一个较大卖出价格,记录较大利益;
2,(1)当较大价格后一天的价格不小于上次较小价格时,递归求后半部分的较大利益,最终取最大
   (2)否则,将后一天价格修改为较小后再同上递归求解。
代码实现:
1
class Solution {
2
public:
3
    int maxProfit(vector<int> &prices) {
4
        //先买后卖,最低价买,最高价卖
5
        if (prices.size() == 0 || prices.size() == 1)
6
            return 0;
7
        //先找到第一个最小价
8
        vector<int>::iterator iter;
9
        for (iter=prices.begin(); iter!=prices.end()-1; ++iter){
10
            if(*iter < *(iter+1))
11
                break;
12
        }
13
        if (iter==prices.end()-1)
14
            return 0;
15
        //找出买后 的最大价格
16
        vector<int>::iterator iter2;
17
        int mx;
18
        for (iter2 = iter+1; iter2<prices.end()-1 && *iter2 < *(iter2+1); ++iter2);
19
        mx = *iter2 - *iter;
20
        //递归
21
        if (iter2<prices.end()-1){
22
            if (*(iter2+1) < *iter){
23
                vector<int> subpri(iter2+1, prices.end());
24
                return max(mx, maxProfit(subpri));
25
            }
26
            else {
27
                *(iter2+1) = *iter;//交换最小价格后递归
28
                vector<int> subpri(iter2+1, prices.end());
29
                return max(mx, maxProfit(subpri));
30
            }
31
        }
32
        
33
        
34
        return mx;
35
    }
36
};
简洁解答:语言:C++ 运行时间: <1 ms 占用内存:8552K 状态:答案正确
 
classSolution {
public:
    
    intmaxProfit(vector<int> &prices) {
        if(prices.size() <= 1)
        {
            return0;
        }
 
        intmax = 0;
 
        for(inti = 0; i < prices.size() - 1; i++)
        {
            for(intj = i + 1; j < prices.size(); j++)
            {
                intpro = prices[j] - prices[i];
                max = pro > max ? pro : max;
            }
        }
 
        returnmax;
    }
};


0 0
原创粉丝点击