Swift4.0 O(n) two solution


  • 0
    K
    class Solution {
        func maxSubArray(_ nums: [Int]) -> Int {
            let n = nums.count
            var maxVal = -2147483648 //结果
            
            var minsi = 0; //最小si
            var sj = 0; //当前sj值
            var si = 0; //当前si值
            for  i in 0 ..< n {
                
                sj += nums[i]
                if (minsi>si) {
                    minsi = si
                }
                if(sj-minsi>maxVal){
                    maxVal = sj - minsi
                }
                si = sj
            }
            return maxVal
        }
    
    }
    
    

    or

    class Solution {
        func maxSubArray(_ nums: [Int]) -> Int {
            let n = nums.count
            var sum = 0
            var maxVal = -2147483648
            for  i in 0 ..< n {
                sum = sum + nums[i]
                maxVal = max(sum, maxVal)
                if(sum < 0){
                    sum = 0
                }
            }
            return maxVal
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.