码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Best Time to Buy and Sell Stock with Cooldown

时间:2016-03-17 02:03:42      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

题目:

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)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

题解:

Best Time to Buy and Sell Stock相似.

有三个状态s0, s1, s2. s0 buy stock 变成s1, s1 sell stock 变成s2.

技术分享

s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1

Time Complexity: O(n). Space: O(n). 

AC Java:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if(prices == null || prices.length == 0){
 4             return 0;
 5         }
 6         int len = prices.length;
 7         int [] s0 = new int[len];
 8         int [] s1 = new int[len];
 9         int [] s2 = new int[len];
10         
11         s0[0] = 0;
12         s1[0] = -prices[0];
13         s2[0] = 0;
14         for(int i = 1; i<len; i++){
15             s0[i] = Math.max(s0[i-1],s2[i-1]);
16             s1[i] = Math.max(s1[i-1], s0[i-1]-prices[i]);
17             s2[i] = s1[i-1] + prices[i];
18         }
19         return Math.max(s0[len-1], s2[len-1]);
20     }
21 }

Reference: https://leetcode.com/discuss/72030/share-my-dp-solution-by-state-machine-thinking

LeetCode Best Time to Buy and Sell Stock with Cooldown

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5285886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!