Compute max profit with two transactions
Java
Hard
5 views
Problem Description
Task: return max profit with at most 2 buy-sell transactions. Use variables for DP states.
Output Format
Return value
Constraints
O(n) time, O(1) space.
Official Solution
static int maxProfit2(int[] p){int buy1=Integer.MIN_VALUE,buy2=Integer.MIN_VALUE;int sell1=0,sell2=0;for(int x:p){buy1=Math.max(buy1,-x);sell1=Math.max(sell1,buy1+x);buy2=Math.max(buy2,sell1-x);sell2=Math.max(sell2,buy2+x);}return sell2;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!