【EASY】Maximum Subarray

发布于: 2018-12-16 21:22
阅读: 32
评论: 0
喜欢: 0

问题

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

More practice: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

分析过程

  • 输入:一个数组:[−2,1,−3,4,−1,2,1,−5,4]
  • 输出:子序列的最大和:6
  • 思路:遍历数组,某个元素前面的所有元素和小于这个元素的话,就舍弃前面所有的元素,从这个元素开始加,可以保证和最大。

解决方法

// 普通解法
func maxSubarray1(_ arr: [Int]) -> Int {
    var maxSum = Int.min
    var cur = 0
    
    for i in arr {
        // 如果和比自己本身就小,则取自己本身
        cur = max(cur + i, i)
        // 更新此时的最大值
        maxSum = max(maxSum, cur)
    }
    
    return maxSum
}

// 分治法
func maxSubarray2(_ arr: [Int]) -> Int {
    return _maxSubarray2(arr, 0, arr.count - 1)
}

func _maxSubarray2(_ arr: [Int], _ left: Int, _ right: Int) -> Int {
    if left >= right {
        return arr[left]
    }
    // 数组一分为二
    let mid = left + (right - left) / 2
    // 左边的最大值
    let lMax = _maxSubarray2(arr, left, mid - 1)
    // 右边的最大值
    let rMax = _maxSubarray2(arr, mid + 1, right)
    // 以下开始计算从中间往两边伸展的数组的最大值
    var mMax = arr[mid]
    var tmp = mMax
    if left <= mid - 1 {
        for i in left...mid - 1 {
            tmp += arr[mid - 1 - i + left]
            mMax = max(mMax, tmp)
        }
    }
    tmp = mMax
    if mid + 1 <= right {
        for i in mid + 1...right {
            tmp += arr[i]
            mMax = max(mMax, tmp)
        }
    }
    return max(lMax, rMax, mMax)
}

let arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(maxSubarray1(arr))
print(maxSubarray2(arr))

Thanks for reading.

All the best wishes for you! 💕