leetcode 121 309

来源:互联网 发布:网络运营主管招聘 编辑:程序博客网 时间:2024/06/05 02:38

比较简单的俩个题,第一题O(n)的复杂度,第二题也想用O(n)的复杂度解决,刚开始出错了,直接用DP,毕竟最爱,虽然是O(n2)的复杂度,运行时间排名yefeichan

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        max_profile=0        if len(prices)==0:        return max_profile        min_price=prices[0]        max_price=prices[0]        for i in range(1,len(prices)):        if prices[i]>max_price:        if max_profile<(prices[i]-min_price):        max_profile=prices[i]-min_price        max_price=prices[i]        if prices[i]<min_price:        min_price=prices[i]        max_price=prices[i]        return max_profile

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 = 3transactions = [buy, sell, cooldown, buy, sell]
class Solution(object):    def maxProfit(self, prices):    max_profile=[0]*(len(prices)+2)    if len(prices)<2:    return 0    for i in range(len(prices)-1,-1,-1):    maxp=max_profile[i+1]    for j in range(i+1,len(prices)):    if prices[j]>prices[i]:    if prices[j]-prices[i]+max_profile[j+2]>maxp:    maxp=prices[j]-prices[i]+max_profile[j+2]    max_profile[i]=maxp    return max_profile[0]