Leetcode 309 Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:域名whois历史查询 编辑:程序博客网 时间:2024/06/16 07:34


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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
莫名想到了状态机。
整个过程在sell 和 buy之间转换,他们之间的关系如下:
最后一定是sell结尾,所以返回的是s0


public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0){            return 0;        }                int b0 = - prices[0];         int b1 = b0;        int s0 = 0;        int s1 = 0;        int s2 = 0;        for(int i = 1; i < prices.length; i++){            b0 = Math.max(b1, s2 - prices[i]);            s0 = Math.max(s1, b1 +prices[i]);            b1 = b0;            s2 = s1;            s1 = s0;        }        return s0;    }}


阅读全文
0 0
原创粉丝点击