Maximum Subarray Difference
Description
Given an array with integers.
Find twonon-overlapping_subarrays_A_and_B, which|SUM(A) - SUM(B)|is the largest.
Return the largest difference.
The subarray should contain at least one number
Example
For[1, 2, -3, 1], return6.
Challenge
O(n) time and O(n) space.
Analysis
与Maximum Subarray系列问题一样,这里其实只用转化问题即,求 max |SUM(A) - SUM(B)|,等价为求
Math.max(ans, Math.max(Math.abs(leftMax(A) - rightMin(B)), Math.abs(leftMin(A) - rightMax(B))))
也就是和之前求 maximum non-overlap subarrays 的思路基本一致,只不过要求的数组变成了四个:leftMax, leftMin, rightMax 和 rightMin
虽然最后代码很长,但是原理很简单,总共5 pass,4次pass用来生成leftMax, leftMin, rightMax 和 rightMin
最后一个pass用来寻找最终的答案。因此时间复杂度O(n), 空间复杂度O(n).
Solution
Kadane's Algorithm - O(n) space, O(n) time (283ms beats 96.40%!)
Last updated
Was this helpful?