Problem:
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).
Solution:
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() < 2)
return 0;
int minSoFar = prices[0];
int maxSoFar = prices[0];
int bestBuy = 0;
int totalMaxBestBuy = 0;
int it;
for(it = 1; it < prices.size(); it++) {
if (prices[it] >= maxSoFar) {
maxSoFar = prices[it];
bestBuy = maxSoFar - minSoFar;
}
else{
// It means prices are going down as well. add previous bestBuy
totalMaxBestBuy = totalMaxBestBuy + bestBuy;
minSoFar = prices[it];
maxSoFar = prices[it];
bestBuy = 0;
}
}
totalMaxBestBuy = totalMaxBestBuy + bestBuy;
return totalMaxBestBuy;
}
};
No comments:
Post a Comment