Leetcode, BestTimeToBuyAndSellStock3
设状态 f(i),表示区间 [0, i](0 ≤ i ≤ n ? 1) 的最大利润,状态 g(i),表示区间 [i, n ? 1](0 ≤ i ≤ n ? 1) 的最大利润,则最终答案为 max {f(i) + g(i)} , 0 ≤ i ≤ n ? 1。 允许在一天内买进又卖出,相当于不交易,因为题目的规定是最多两次,而不是一定要两次。(https://gist.github.com/soulmachine/)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int solution( vector<int> &prices )
{
const int n = prices.size();
if (n < 2) return 0;
vector<int> f(n, 0);
vector<int> g(n, 0);
for ( int i = 1, valley = prices[0]; i < n; ++i )
{
f[i] = std::max(f[i - 1], prices[i] - valley);
valley = std::min(valley, prices[i]);
}
for ( int i = n - 2, peak = prices[n - 1]; i >= 0; --i)
{
g[i] = std::max( g[i], peak - prices[i] );
peak = std::max( peak, prices[i]);
}
int max_profit = 0;
for ( int i = 0; i < n; ++i )
{
max_profit = std::max( max_profit, f[i] + g[i] );
}
return max_profit;
}
int main()
{
vector<int> prices = { 3,3,5,0,0,3,1,4 };
vector<int> prices1 = { 1,2,3,4,5 };
vector<int> prices2 = { 7,6,4,3,1 };
vector<int> prices3 = { 1 };
cout << solution(prices) << endl;
cout << solution(prices1) << endl;
cout << solution(prices2) << endl;
cout << solution(prices3) << endl;
return 0;
}
|