首页 > 其他 > 详细

LeetCode: Best Time to Buy and Sell Stock III

时间:2014-03-04 03:57:43      阅读:546      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

bubuko.com,布布扣
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0) return 0;
        int maxProfit = 0;
        int maxp1 = 0;
        int maxp2 = 0;
        int minp1 = prices[0];
        int minp2 = INT_MAX;
        for(int i = 1;i < prices.size();i++){
            int diff1 = prices[i] - minp1;
            if(diff1 < 0){
                minp1 = prices[i]; 
            }else if(diff1 > maxp1){
                maxp1 = diff1;
            }
            
            if(i < prices.size() - 1){
                for(int j = i; j < prices.size();j++){
                    int diff2 = prices[j] - minp2;
                    if(diff2 < 0){
                        minp2 = prices[j];
                    }else if(diff2 > maxp2){
                        maxp2 = diff2;
                    }
                }
            }else{
                maxp2 = 0;
            }
            maxProfit = (maxp1 + maxp2) > maxProfit ? maxp1 + maxp2:maxProfit;
        }
        return maxProfit;
    }
};
bubuko.com,布布扣

Submission Result: Time Limit Exceeded 

在大测试数据面前,还是过不了。

 

 

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

LeetCode: Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/yeek/p/3578619.html

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