How to find three consecutive numbers with the largest sum in an array of integers in Swift

1 Answer

0 votes
// findMaxSumOfThree finds 'k' consecutive numbers with the largest sum in an array.
// Returns an optional tuple containing the maximum sum and the subsegment, or nil if invalid.
func findMaxSumOfThree(_ numbers: [Int], _ k: Int) -> (sum: Int, numbers: [Int])? {
    // Validate input parameters: k must be positive and array count at least k
    guard k > 0, numbers.count >= k else { return nil }
    
    // Compute the sum of the initial window of size k
    var currentSum = 0
    for i in 0..<k {
        currentSum += numbers[i]
    }
    
    var maxSum = currentSum
    var maxStartIndex = 0
    
    // Slide the window across the remaining elements:
    // Subtract the element leaving on the left, add the element entering on the right.
    for i in k..<numbers.count {
        currentSum = currentSum - numbers[i - k] + numbers[i]
        
        if currentSum > maxSum {
            maxSum = currentSum
            maxStartIndex = i - k + 1
        }
    }
    
    // Extract the subsegment with the maximum sum safely
    let maxNumbers = Array(numbers[maxStartIndex..<maxStartIndex + k])
    return (maxSum, maxNumbers)
}

// Example usage:
let numbers = [4, 2, 0, 8, 7, 5, 1, 3, 9, 6]
let k = 3

if let result = findMaxSumOfThree(numbers, k) {
    print("Largest sum: \(result.sum)")
    // Format the numbers space-separated to match the example requirement
    let formattedNumbers = result.numbers.map(String.init).joined(separator: " ")
    print("Numbers: \(formattedNumbers)")
} else {
    print("Invalid parameters or array too short.")
}


/*
run:

Largest sum: 20
Numbers: 8 7 5

*/

 



answered Oct 30 by avibootz

Related questions

...