From 6f06cbdb31ee8cf1c39b279aef129aa72e41e77e Mon Sep 17 00:00:00 2001 From: Roshan Kumar Sah Date: Sat, 13 Feb 2021 19:15:07 +0530 Subject: [PATCH] Update MaxConsecutiveOnes.swift 1. Empty Case handling 2. Better naming --- Array/MaxConsecutiveOnes.swift | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/Array/MaxConsecutiveOnes.swift b/Array/MaxConsecutiveOnes.swift index 6da8ee90..d5fca01f 100644 --- a/Array/MaxConsecutiveOnes.swift +++ b/Array/MaxConsecutiveOnes.swift @@ -7,17 +7,26 @@ class MaxConsecutiveOnes { func findMaxConsecutiveOnes(_ nums: [Int]) -> Int { - var globalMax = 0, localMax = 0 + // Output + var maximumConsecutiveSum = 0 - for num in nums { - if num == 1 { - localMax += 1 - globalMax = max(globalMax, localMax) + guard !nums.isEmpty else { + return maximumConsecutiveSum + } + + var currentRunningSum = 0 + for eachNumber in nums { + if eachNumber == 1 { + currentRunningSum += 1 } else { - localMax = 0 + currentRunningSum = 0 + } + + if currentRunningSum > maximumConsecutiveSum { + maximumConsecutiveSum = currentRunningSum } } - return globalMax + return maximumConsecutiveSum } -} \ No newline at end of file +}