Package Level3;/*** Best Time to Buy and keep 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 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 s Tock before you buy again ). **/public class S122 {public static void main (String [] args) {int [] prices = {2, 1, 2, 0, 4}; System. out. println (maxProfit (prices);} // greedy method. This question is different from the previous Best Time to Buy and Stock. This question can be used to Buy and Sell stocks multiple times, // to earn the price difference. Therefore, in greedy mode, the basic idea is to lock a low price, and then throw the stock when the price rises to the local highest point // (that is, the price will decrease in the next day, the lower price of the next day is used as a purchase, and then calculated. // Pay attention to the final processing of the final profit public static int maxProfit (int [] prices) {if (prices. length = 0) {return 0;} int totalProfit = 0; int startIndex = 0; int I; for (I = 1; I <prices. length; I ++) {if (prices [I] <prices [I-1]) {totalProfit + = prices [I-1]-prices [startIndex]; startIndex = I ;}} // if (prices [I-1]> prices [startIndex]) {totalProfit + = prices [I-1]-prices [startIndex];} return totalProfit ;}}