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 at most k transactions.
public class Solution { public int maxProfit(int k, int[] prices) { if (prices == null || prices.length == 0) { return 0; } if (k > prices.length) { int res = 0; for (int i = 0; i < prices.length-1; i++) { int tmp = prices[i + 1] - prices[i]; if (tmp > 0) { res += tmp; } } return res; } int[][] global = new int[prices.length][k+1]; int[][] local = new int[prices.length][k+1]; for (int i = 0; i < prices.length-1; i++) { int tmp = prices[i + 1] - prices[i]; for (int j = 0; j < k; j++) { local[i+1][j+1] = Math.max(global[i][j]+Math.max(tmp,0), local[i][j+1] + tmp); global[i+1][j+1] = Math.max(global[i][j+1], local[i+1][j+1]); } } return global[prices.length-1][k]; } }