贪心专题5 - leetcode53. Maximum Subarray/122. Best Time to Buy and Sell Stock II

53. Maximum Subarray

题目描述

给定整数数组 nums ,找到一个有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

例子

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

思想
贪心。记录到当前位置的和,只要和大于0,则继续和后面相加;否则summ置0。

解法

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = summ = nums[0]
        for num in nums[1:]:
            if summ < 0:
                summ = 0
            summ += num
            res = max(res, summ)
        return res
122. Best Time to Buy and Sell Stock II

题目描述

给定一个数组,它的第 i 个元素是给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

例子

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.

Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

思想
只要卖出的价格比买进的高,都想卖出,且想以最高价卖出。贪心:只需关注递增的差值,求和
此时我们来看[1,2,3,4,5],在price=1买入,price=5卖出;等价于(5-4)+(4-3)+(3-2)+(2-1)。所以只要次日比前日价格高,我们就进行卖出交易,最终利润可以最大化。

解法

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        res = 0
        for i in range(len(prices)-1):
            res += max(prices[i+1] - prices[i], 0)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值