[ITint5] Maximum Subarray for a Circular Array

http://www.itint5.com/oj/#8
Classic DP problem, which has also appeared in Leetcode as Maximum subarray. The only difference is, in this problem, empty subarray (where sum is 0) is allowed. So instead of return ret, we could simply return max(0, ret).

http://www.itint5.com/oj/#9
Calculate the maximum subarray for a circular array. For example, [1, 3, -2, 6, -1], we should return 9 since 6 + (-1) + 1 + 3 = 9.

The following solution might not be optimized. Suppose that the maximum subarray is from A[i] to A[j]. The idea is, consider the following different scenarios:
  1. i <= j: it is the same as classic problem.
  2. i > j: the sum is A[i : end] + A[start : j]. So we can use two additional arrays:
    • left[j] = maximum subarray, starts from A[start] and ends no later than A[j]
    • right[i] = maximum subarray, starts no earlier than A[i] and ends at A[end]
The following code passes the online judge. However, we need O(4n) in time and O(2n) in space. Not sure how to improve this.

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. A=[1,4,6,-9,10, -11, 8, -2, -7, 9 ,-5 1, 2, 0]

    1. O(n): start from each negative, if its right is also negative, add to itself, if its right >=0, sum them up (until next negative)
    ==> B=[-9, 10, -11, 8, -9, 9 -5 14] , and record their array A index.


    2. Start from each negative, if its right + itself >=0, sum it into array C, if not, put itself in array C:
    ==> C=[11, 1, -11, 8, 0, 9]
    array B always has 1 negative and one positive, so, by using i=i+2, our O(n/2)
    If there is no merge happens in the step, simply pick the biggest positive in B as the biggest block

    3. use hash map to remember negative's position in C, and from each negative, find its right neighbor positive's sum, ==> D=[-11, 29]
    O(n/2).

    Total should be O(2n), space is also O(2n)

    now we found the biggest sub array, starting from -11 and circulate back to the point before itself.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. O(n) time O(1) space solution

    1. Compute SUM = A[0] + ... + A[n-1]
    2. Use DP to solve the original maximum subarray as on LeetCode. Mark solution as MAX
    3. Solve for the minimum subarray. This can be solve with the same DP as for maximum subarray but treat each A[i] as -A[i]. Mark solution as MIN. One caveat, if all numbers in A are >= 0, MIN should be set to 0.
    4. Return max(MAX, SUM-MIN)

    ReplyDelete

Post a Comment

Popular posts from this blog

Maximum Gap

[CC150] Chapter 8 Object-Oriented Design