SubArray
53 Maximum Subarray I
Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
DP
dp[i]: in array[0-i], maximum subarray sum
def maxSubArray(self, nums: List[int]) -> int:
# sum if current accumulate starting from possible counting poinnt
ans = s = nums[0]
for n in nums[1:]:
if s < 0:
s = 0
s += n
ans = max(ans, s)
return ansMaximum Subarray II
Given an array of integers, find two non-overlapping subarrays which have the largest sum. The number in each subarray should be contiguous. Return the largest sum.
Traverse from left and record the minimum subarray at left[i]
Traverse from right and record the minimum subarray at right[i]
split at index i to find the maximum
Maximum Subarray III
Given an array of integers and a number k, find k non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
localMax[i][j]: the max sum must containing i in the j partition
globalMax[i][j]: the max sum may not containing i in the j partition
Func: local[i][j]=max(local[i-1][j], global[i-1][j-1])+nums[i-1], global[i][j]=max(local[i][j],global[i-1][j])
Init: local[i-1][i] = global[i-1][i]=MIN, i=1-k
Ans: global[len][k]
Minimum Subarray
Given an array of integers, find the subarray with smallest sum.
Return the sum of the subarray.
Maximum Subarray Difference
Given an array with integers.
Find two non-overlapping subarrays A and B, which |SUM(A) - SUM(B)| is the largest.
Return the largest difference.
Traverse from left, record the maxSubarray and minSubarray
Traverse from right, record the minSubarray and maxSubarray
diff = leftMax[i] - rightMin[i+1]
643 Maximum Average Subarray
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Use sliding window technique
644 Maximum Average Subarray II
Google
Binary Search
Last updated
Was this helpful?