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]
最大子数组III:寻找最大和的k个不重叠子数组
本文介绍了一个解决在整数数组中找到最大和的k个不重叠子数组的问题,每个子数组的数字在数组中的位置连续。文章详细分析了解决方案,并提供了Python代码实现,满足了时间复杂度为O(n)的要求。
3756

被折叠的 条评论
为什么被折叠?



