LintCode -- 最大子数组 III

LintCode -- maximum-subarray-iii(最大子数组 III)



给定一个整数数组和一个整数k,找出k不重叠子数组使得它们的和最大。

每个子数组的数字在数组中的位置应该是连续的。

返回最大的和。

您在真实的面试中是否遇到过这个题?  
Yes
样例

给出数组[-1,4,-2,3,-2,3]以及k=2,返回 8

注意

子数组最少包含一个数

挑战

要求时间复杂度为O(n)

分析:
只能做到 O(nk) 时间。
mustTheLast[ i ][ j ] 表示前 i 个数中 j 个子数组的最大子数组和,且第 i 个数是第 j 个子数组的元素。
notTheLast[ i ][ j ] 表示前 i 个数中 j 个子数组的最大子数组和,且第 i 个数不一定是第 j 个子数组的元素。

****时间复杂度 O(nk),  空间复杂度 O(nk) ****

代码(Python):
class Solution:
    """
    @param nums: A list of integers
    @param k: An integer denote to find k non-overlapping subarrays
    @return: An integer denote the sum of max k non-overlapping subarrays
    """
    def maxSubArray(self, nums, k):
        # write your code here
        #mustTheLast[i][j] repesent the number i of nums must be the last number in the j-th subarrays.
        #notTheLast[i][j] repesent the number i of nums can be the last number in the j-th subarrays or not.
        n = len(nums)
        mustTheLast = [[-1e9 for i in range(k+1)] for j in range(n+1)]
        notTheLast = [[-1e9 for i in range(k+1)] for j in range(n+1)]
        mustTheLast[0][0] = 0
        notTheLast[0][0] = 0
        for i in range(1, n+1):
            mustTheLast[i][0] = 0
            notTheLast[i][0] = 0
            for j in range(1, k+1):
                mustTheLast[i][j] = max(notTheLast[i-1][j-1] + nums[i-1], mustTheLast[i-1][j] + nums[i-1])
                notTheLast[i][j] = max(mustTheLast[i][j], notTheLast[i-1][j])
        return notTheLast[n][k]


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值