Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).
Greedy + recursive
Buy a stock of the lowest price before the node where the stock price is lowered, sell at the node before the stock is lowered, and recursively
public class Solution {int sum = 0; public int Maxprofit (int[] prices) { if (prices.length<1) return 0; Maxprofit (prices,0); return sum; } private void Maxprofit (int []prices,int start) { if (start>=prices.length-1) return; int buy = Prices[start]; int buyindex = start; for (int i=start+1;i<prices.length;i++) { if (prices[i]<=buy) { buy = Prices[i]; Buyindex = i; } else{break ; } } int sell = Prices[buyindex]; int sellindex = Buyindex; for (int i=buyindex+1;i<prices.length;i++) { if (Prices[i]>=sell) { sell = prices[i]; Sellindex = i; } else{break ; } } sum + = Sell-buy; Maxprofit (prices,sellindex+1); }}
[Leetcode] best time to Buy and Sell Stock II