Thursday, July 23, 2015

subarray with max sum in array

Based on max contiguous sum in array i.e. subarray with max sum.
// max sum
(a):
    sum = 0, maxsum = a[0] // 1st element for -ve values
    for i = 0, i < a.length, i++:
        sum += a[i]
        if sum > maxsum:
            maxsum = sum
        if sum < 0:
            sum = 0
    return maxsum
// contiguous subarray max sum
// handles all -ve values, excludes 0s, longer subarray does not matter
(a):
    if a == null || a.length == 0:
        throw
    sum = 0, maxsum = a[0] // 1st element for -ve values
    start = 0, maxstart = 0
    end = 0, maxend = 0
    for i = 0, i < a.length, i++:
        sum += a[i]
        // works for -ve values due to order of ifs and maxsum = a[0]
        if sum > maxsum:
            maxsum = sum
            end = i
            maxstart = start
            maxend = end
        if sum < 0:
            sum = 0
            start = i +1
    return maxsum, maxstart, maxend
//examples
              |     |
a:   5  5 -20 5  5  5
sum: 5 10   0 5 10 15

     |  |
a:   5  5 -20 2 3  5
sum: 5 10   0 2 5 10

        |
a:   -3 0 -2
sum:  0 0  0

     |    |
a:   2 3  5 -20 5  5 0
sum: 2 5 10   0 5 10 0

      |
a:    2 -2 2
sum:  2  0 2

      |
a:    0 0 0
sum:  0 0 0

         |
a:   -3 -1 -2
sum:  0  0  0
// largest contiguous subarray max sum
// handles all -ve values, includes 0s, longer subarray
(a):
    if a == null || a.length == 0:
        throw
    sum = 0, maxsum = a[0]
    start = 0, maxstart = 0
    end = 0, maxend = -1
    for i = 0, i < a.length, i++:
        sum += a[i]
        // works for -ve values due to order of ifs and maxsum = a[0]
        if sum > maxsum:
            maxsum = sum
            end = i
            maxstart = start
            maxend = end
        // when sum and maxsum are equal, take longer subarray
        else if sum == maxsum:
            end = i
            if (end-start) > (maxend-maxstart):
                maxstart = start
                maxend = end
        if sum < 0:
            sum = 0
            start = i +1
    return maxsum, maxstart, maxend
//examples
              |     |
a:   5  5 -20 5  5  5
sum: 5 10   0 5 10 15

              |    |
a:   5  5 -20 2 3  5
sum: 5 10   0 2 5 10

        |
a:   -3 0 -2
sum:  0 0  0

     |    |
a:   2 3  5 -20 5  5 0
sum: 2 5 10   0 5 10 0

      |    |
a:    2 -2 2
sum:  2  0 2

      |   |
a:    0 0 0
sum:  0 0 0

      |   |
a:    0 0 0 -1 0
sum:  0 0 0  0 0

      |     |
a:    1 0 0 0 -1 0
sum:  1 0 0 0  0 0

         |
a:   -3 -1 -2
sum:  0  0  0
[Hat tip to JE, AP]

No comments:

Post a Comment