Swift solution - Prefix Sum + Two Pointers


  • 0
    class Solution {
        func findMaxAverage(_ nums: [Int], _ k: Int) -> Double {
            var prefixSum = [Int](repeatElement(0, count: nums.count))
            var result = Double(Int.min)
            var left = 0
            var right = k - 1
            
            prefixSum[0] = nums[0]
            for i in 1..<nums.count {
                prefixSum[i] = nums[i] + prefixSum[i - 1]
            }
            
            while right < nums.count {
                result = max(result, Double(prefixSum[right] - prefixSum[left] + nums[left]) / Double(k))
                right += 1
                left += 1
            }
            
            return result
        }
    }
    

Log in to reply
 

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