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).
An example will make everything clear!
Suppose we have stock prices as follows:
prices : [1, 2, 3, 1, 2]:
Since I can take as many transactions as I like. A clear buyer will first buy prices[0], waiting till prices[2], sell the stocks, she can earn 2. Then buy at prices[3] and sell at prices[4]. The main rule here is to buy at lowest price and wait till the top sharp price to sell. But, she need to pay attention to such a condition...
#include <vector> #include <iostream> using namespace std; int maxProfit(vector<int>& prices) { if(prices.size() <= 1) return 0; int profits = 0; int maxProfit = 0; int minPrice = prices[0]; int i = 1, j = 0; while(i < prices.size()) { if(prices[i] > prices[j]) { ; // since the stocks are in increasing trend, only idiot will sell... } else { profits += (prices[j] - minPrice); // it falls down, sell it! maxProfit = max(maxProfit, profits); minPrice = prices[i]; } i++; j++; } if(prices[i-1] > minPrice) maxProfit += prices[i-1] - minPrice; // pay attention to the last one. return maxProfit; } int main(void) { vector<int> prices{1, 5, 3, 1, 2, 3}; int profits = maxProfit(prices); cout << profits << endl; }