Best Time to Buy and Sell Stock II
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
-------------------------------- thinking ---------------------------------------------------one important bug:
when up is true and the final ele should be considered to sell !!!
----------------------------------- greedy method-------------------------------------
You make profit by buying low and selling high, so a person would buy at trough and sell at crest, here the subtle thing is it is equivalent to buying at i and selling at i + 1 as long as price is increasing, this is fine because you can do as many transactions as you want.
Suppose the prices are
1 2 3 4 5
then
-------------------------------- codes ----------------------------------------------------5 - 1 == 2 - 1 + 3 - 2 + 4 - 3 + 5 - 4
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() <= 1) {
return 0;
}
int up;
if (prices[0] < prices[1]) {
up = false;
} else {
up = true;
}
int lowest = prices[0];
int result = 0;
for (int i = 1; i < prices.size(); i++) {
if (up && prices[i] < prices[i-1]) {
up = false;
result += prices[i-1] - lowest;
} else if (!up && prices[i] > prices[i-1]) {
up = true;
lowest = prices[i-1];
}
}
//bug here
if (up) {
result += prices[prices.size() - 1] - lowest;
}
return result;
}
};
No comments:
Post a Comment