股票收益最大問題

題目: 給定數組n, 包含n天股票的價格price, 一我的一共最多能夠買2手股票,但在第一手股票賣出去前不能買入第二手股票. 若是不買,收益爲0. 假設每手只買1股,計算這我的最大收益.ios

答案:數組

#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;
}
相關文章
相關標籤/搜索