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 ).
Question 2: Buy and buy stocks. The change from 1 to 1 is that you can buy and sell any number of times, but you must make sure that you can do it for the second time after buying and selling.
Analysis: it is actually to find the length and of all the rising segments of the wavy line.
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if (prices.length<=1) { 4 return 0; 5 } 6 7 int[] profits=new int[prices.length-1]; 8 int maxprofit=0; 9 for (int i = 0; i < profits.length; i++) {10 profits[i]=prices[i+1]-prices[i];11 }12 13 for (int i : profits) {14 if (i>0) {15 maxprofit=maxprofit+i;16 }17 }18 return maxprofit;19 }20 }
Leetcode best time to buy and other stock II