Skip to content

Commit

Permalink
Minor refactor.
Browse files Browse the repository at this point in the history
  • Loading branch information
AnnieKim committed Aug 21, 2013
1 parent 3bd7e23 commit d0b5a61
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions BestTimetoBuyandSellStockIII.h
@@ -1,6 +1,7 @@
/*
Author: Annie Kim, anniekim.pku@gmail.com
Date: Apr 28, 2013
Update: Aug 22, 2013
Problem: Best Time to Buy and Sell Stock III
Difficulty: Medium
Source: http://leetcode.com/onlinejudge#question_123
Expand All @@ -10,36 +11,37 @@
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution: dp.
Solution: dp. max profit = max { l2r[0...i] + r2l[i+1...N-1] }.
0 <= i <= N-1
*/

class Solution {
public:
int maxProfit(vector<int> &prices) {
int N = prices.size();
vector<int> l2r(N, 0); // [1, i]
vector<int> r2l(N, 0); // [i + 1, N]

int imin = 0;
if (N <= 1) return 0;

int l2r[N], r2l[N];
l2r[0] = 0;
r2l[N-1] = 0;

int minn = prices[0];
for (int i = 1; i < N; ++i)
{
if (prices[i] < prices[imin])
imin = i;
l2r[i] = max(l2r[i-1], prices[i] - prices[imin]);
minn = min(minn, prices[i]);
l2r[i] = max(l2r[i-1], prices[i] - minn);
}

int imax = N - 1;
for (int i = N - 3; i >= 0; --i)
int maxx = prices[N-1];
for (int i = N-2; i >= 0; --i)
{
if (prices[i+1] > prices[imax])
imax = i + 1;
r2l[i] = max(r2l[i+1], prices[imax] - prices[i+1]);
maxx = max(maxx, prices[i]);
r2l[i] = max(r2l[i+1], maxx - prices[i]);
}

int res = 0;
for (int i = 0; i < N; ++i)
res = max(res, l2r[i] + r2l[i]);
int res = l2r[N-1];
for (int i = 0; i < N-1; ++i)
res = max(res, l2r[i] + r2l[i+1]);
return res;
}
};

0 comments on commit d0b5a61

Please sign in to comment.