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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
class Solution {
public:
int maxProfit(vector<int> &array) {
int n = array.size();
if (n < 2)
return 0;
int forward[n], backward[n], min_so_far, max_so_far, ret = 0;
min_so_far = array[0];
max_so_far = array[n - 1];
forward[0] = 0;
backward[n-1] = 0;
for (int i = 1; i < n; i++) {
if (array[i] >= min_so_far) {
forward[i] = max(forward[i-1], array[i] - min_so_far);
} else {
min_so_far = array[i];
forward[i] = forward[i-1];
}
}
for (int i = n - 2; i >= 0; i--) {
if (array[i] <= max_so_far) {
backward[i] = max(backward[i+1], max_so_far - array[i]);
} else {
max_so_far = array[i];
backward[i] = backward[i+1];
}
}
for (int i = 0; i < n; i++) {
ret = max(forward[i] + backward[i], ret);
}
return ret;
}
};
No comments:
Post a Comment