53. Maximum Subarray

75 阅读1分钟

题目描述

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

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

解题思路

这个问题的主要思想是: 在循环过程中,
1. 我们先判断之前数的和与加上当前item以后的和大小,
2. 然后在比较上次结果与我们第一判断的结果, 就可以得到最大值
3. 这里我们又给小技巧, 先赋值nums[0], 然后直接从index=1开始遍历,我们就可以直接处理nums只有一个值的情况
时间复杂度: O(n )

示例代码

func maxSubArray(_ nums: [Int]) -> Int {
    var add = nums[0]
    var result = add
    for i in 1..<nums.count {
        add = max(nums[i], add + nums[i])
        result = max(result, add)
    }
    return result
}