8.9 练手 腾讯50题 122

Leetcode 122. Best Time to Buy and Sell Stock II

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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

 

方法是直接找数组中递增序列的位置,因此多开了一个数组记录递增序列出现的初始位置,最后相加就好。代码如下:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n <= 1:
            return 0
        
        output = 0
        a = [0] * n
        for i in range(n-1):
            if(prices[i] < prices[i+1]):
                a[i] = 1
        i = 0
        while(i <= n-2):
            low = 0
            high = 0
            if a[i] == 1:
                low = prices[i]
                high = prices[i+1]
                while(a[i+1] == 1):
                    i = i+1
                    high = prices[i+1]
                output = output + (high-low)
            i = i + 1            
        return output

途中遇到的问题是,我发现python的range迭代器和for还是有区别的,比如i++的操作循环一遍就没用了。其实也可以直接离散的两两减,不用看成序列,结果不变只是操作麻烦而已。

速度beat 95%+

 

其他答案:

1.很有意思的一行代码,用zip用得很开心:

def maxProfit(self, prices):
    return sum(y-x for x, y in zip(prices[:-1], prices[1:]) if y > x)

2.动态规划,虽然代码差不多,但是想法不同啊

设置走的路为天数 即 n,每天的状态转移方程为:

dp[i] = dp[i-1] if prices[i]<=prices[i-1] else dp[i-1]+(prices[i]-prices[i-1])

代码为:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # dp[i] = dp[i-1] if prices[i]<=prices[i-1] else dp[i-1]+(prices[i]-prices[i-1])
        res = 0
        for i in range(1,len(prices)):
            if prices[i]>prices[i-1]:
                res += (prices[i]-prices[i-1])
        return res

参考:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/mai-mai-gu-piao-de-zui-jia-shi-ji-iipython3bian-li/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值