首页 > 其他 > 详细

Best Time to Buy and Sell Stock

时间:2014-03-05 01:49:25      阅读:537      评论:0      收藏:0      [点我收藏+]

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.

vector下标,初始化

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0)return 0;
        int s = prices.size();
        vector<int> min(s,prices[0]);
        vector<int> max(prices.size(),prices[prices.size()-1]);
         
        //min.push_back(prices[0]);
        for(int i = 1 ; i < s ; i++)
        if(min[i - 1] > prices[i]) min[i] = prices[i];
        else min[i] = min[i-1];
         
        //max.push_back(prices[s-1]);
        for(int j = s-2 ; j >= 0 ; j --)
        if(prices[j] > max[j+1]) max[j] = prices[j];
        else max[j] = max[j+1];
         
        int pro = 0 ;
        for(int i = 0 ; i < s ;i++)if(pro < max[i] - min[i]) pro = max[i] - min[i];
        return pro;
    }
};

  更简单的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.size() == 0) {
            return 0;
        }
        int min = prices[0], profit = 0;
        for (int i = 1; i < prices.size(); i++) {
            profit = prices[i] - min > profit ? prices[i] - min : profit;
            min = prices[i] < min ? prices[i] : min;
        }
        return profit;
    }
};

  空间上更优

Best Time to Buy and Sell Stock,布布扣,bubuko.com

Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/pengyu2003/p/3580404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!