股票收益最大问题

题目:
给定数组n, 包含n天股票的价格price,
一个人一共最多可以买2手股票,但在第一手股票卖出去前不能买入第二手股票.
如果不买,收益为0.
假设每手只买1股,计算这个人最大收益.

答案:

#include <iostream>
#include <vector>

// 计算[first,last)之间的最大子序列和,并将每一步保存在result中
template<class Iterator, class T>
void MaxSubArray(Iterator first, Iterator last, std::vector<T> &result)
{
    T max = 0;
    T sum = 0;
    for(;first!=last;first++){
        if(sum<0){
            sum = 0;
        }
        sum += *first;
        max = max>sum?max:sum;
        result.push_back(max);
    }
}

// 计算最大收益
int MaxProfit(const std::vector<int> &prices)
{ 
    if(prices.size()<2){
        return 0;
    }

    // prices数组转换为涨跌幅数组
    std::vector<int> v;
    for(int i=1;i<prices.size();i++){
        v.push_back(prices[i]-prices[i-1]);
    }
    
    // 从左到右计算每个最大子序列和
    std::vector<int> left;
    left.push_back(0);
    MaxSubArray(v.begin(),v.end(),left);
 
    // 从右到左计算每个最大子序列和
    std::vector<int> right;
    right.push_back(0);
    MaxSubArray(v.rbegin(),v.rend(),right);
    
    // 将数组分为左右两部分,左右相加求最大值
    int max = 0;
    auto iterLeft = left.begin();
    auto iterRight = right.rbegin();
    for(;iterLeft != left.end(); iterLeft++, iterRight++){
        int tmp = *iterLeft + *iterRight;
        max = max>tmp?max:tmp;
    }
 
    return max;
}


int main()
{
    std::vector<int> prices = {3,8,5,1,7,8};
    int result = MaxProfit(prices);
    std::cout<<result<<std::endl;

    return 0;
}
posted @ 2018-12-20 00:51  yvhqbat  阅读(308)  评论(0编辑  收藏  举报