Best time to buy and stock Stock II
Say you have an array for whichITh element is the price of a given stock on dayI.
Design an algorithm to find the maximum profit. you may complete as your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the stock before you buy again)
C ++ version:
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.size() == 0) { return 0; } int profit = 0; for(int i = 1; i < prices.size(); i++) { profit+=prices[i]-prices[i-1]>0?prices[i]-prices[i-1]:0; } return profit; }};
Java version:
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) { return 0; } int profit = 0; for(int i = 1; i < prices.length; i++) { profit+=prices[i]-prices[i-1]>0?prices[i]-prices[i-1]:0; } return profit; }}
Best time to buy and stock Stock II