标签:
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.
解题思路:要求两次交易的最大利润.将整个序列分两个区别来讨论,分别计算两个区间的最大值.
若用两个循环来遍历则重复的计算过多.因此利用动态规划的思想首先记录买入日为i的最大利润p[i];
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int maxProfit(vector<int> &prices) {
int N = prices.size();
if (N <=1)
return 0;
vector<int>p(N, 0);
for (int idx_buy = N - 2,idx_sell = N-1; idx_buy >= 0; --idx_buy){
int Profit = prices[idx_sell] - prices[idx_buy];
idx_sell = Profit < 0 ? idx_buy : idx_sell;
p[idx_buy] = Profit>p[idx_buy + 1] ? Profit : p[idx_buy + 1];
}
int MaxProfit = 0;
for (int idx_buy = 0, idx_sell = 1; idx_sell < N;++idx_sell)
{
int Profit = prices[idx_sell] - prices[idx_buy];
idx_buy = Profit < 0 ? idx_sell : idx_buy;
MaxProfit = Profit + p[idx_sell]>MaxProfit ? Profit + p[idx_sell] : MaxProfit;
}
return MaxProfit;
}
Best Time to Buy and Sell Stock III
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44060959