How to find the maximum value we can achieve by picking k elements from a list in Swift

1 Answer

0 votes
import Foundation

func maxSumOfK(_ arr: [Int], _ k: Int) -> Int {
    let sorted = arr.sorted(by: >)   // descending
    return sorted.prefix(k).reduce(0, +)
}

let arr = [11, 2, 4, 9, 3, 6, 5, 1]
let k = 3

print(maxSumOfK(arr, k))  


/*
run:
 
26
 
*/

 



answered Apr 6 by avibootz

Related questions

...