I got an interview question where I need to do k operation on an array and get the sum of final array.
For each iteration, any random element needs to be picked, divide it by 2 and replace the the value with existing value in array.
arr = [20,10,7]
Pick 7, divide it by 2 and replace 7 with ceil value of the result , output for first iteration will be
[20,10,4]
I wrote the code which is working fine but apparently it is not an optimal solution. It is taking a lot of time for large input.I found a few solutions on stack overflow in other languages but not in iOS related languages.
How can I achieve an optimal solution?
func minimumSum(numbers:[Int] , iterations:Int) -> Int {
var arr = numbers
guard arr.count > 1 else{
return 0
}
var count = 0
repeat{
if let randomNumber = arr.max(){
// print(randomNumber)
let divided:Int = Int((Double(randomNumber) / 2).rounded())
let indexOfNumber = arr.firstIndex(of: randomNumber)
arr[indexOfNumber!] = divided
count = count + 1
print(count)
}
}while count < iterations
return arr.reduce(0,+)
}