12. The algorithm is simple and swift, and the maximum subsequence

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91528595

Given the nums an array of integers, and find a maximum of the successive sub-array (sub-array comprising a minimum element) having its maximum and returns.

Example:

Input: [-2,1, -3,4, -1,2,1, -5,4],
output: 6
Explanation: continuous subarray [4, -1,2,1], and the maximum was 6 .

solution:

func maxSubArray(_ nums: [Int]) -> Int {
        var sum = 0
        var max_sub_sum = nums[0]
        for num in nums{
            sum += num
            //用当前sum去和第一个元素比较
            if sum > max_sub_sum{
                max_sub_sum = sum
            }
           //如果值为负数那么 sumy一直为0
            if sum < 0{
                sum = 0
            }
        }
        return max_sub_sum
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91528595