Leetcode 309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:迪拜购物 知乎 编辑:程序博客网 时间:2024/04/29 19:02
State machine graph
 /** * state machine approach * state a(hold): hold stack, sell or rest * state b(sold): just sold stack can only rest * state c(rest): cooldown, buy or rest * translate to formula,  * stateA = max(preStateA, preStateC-prices[i]) * stateB = preStateA+prices[i] * stateC = max(preStateB, preStateC) */ public class Solution {    public int maxProfit(int[] prices) {        if (prices.length < 2) return 0;                // initialization        int hold = -prices[0];        int sold = Integer.MIN_VALUE;        int rest = 0;                for (int i=1; i<prices.length; i++) {            int preHold = hold;            hold = Math.max(hold, rest-prices[i]);            rest = Math.max(rest, sold);            sold = preHold + prices[i];        }                return Math.max(sold, rest);    }}

0 0
原创粉丝点击