Buy and Sell Stock with at most k transactions
In share trading, a buyer buys shares and sells on a future date. 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. A new transaction can only start after the previous transaction is complete.
Discussion :
Design an algorithm to find the maximum profit. You may complete at most k transactions. A new transaction can only start after the previous transaction is complete.
Discussion :
public int maxProfit(int k, int[] prices) { int len =prices.length; if(len==0)return 0; int profit[][] = new int[k+1][len]; for(int i=1;i<k+1;i++){ int maxthusfar = Integer.MIN_VALUE; for(int j=1;j<len;j++){ maxthusfar = Math.max(maxthusfar, profit[i-1][j-1]-prices[j-1]); profit[i][j] = Math.max(profit[i][j-1], maxthusfar + prices[j]); } } return profit[k][len-1]; }
Comments
Post a Comment