How Many Apples Can You Put Into the Basket

Straightforward solution for this easy problem

class Solution {
    fun maxNumberOfApples(arr: IntArray): Int {
        var sum = 0
        var ctr = 0
        val sorted = arr.sorted()
        for(item in sorted){
            sum += item
            ctr++
            if(sum >= 5000) break    
        }
        
        if(sum > 5000){
            for(item in (sorted.size - 1 downTo 0)){
                sum -= sorted[item]
                ctr--
                if(sum <= 5000) break
            }    
        }
        
        
        
        return ctr
        
    }
}
Runtime: 208 ms, faster than 28.57% of Kotlin online submissions for How Many Apples Can You Put into the Basket.
Memory Usage: 37.6 MB, less than 100.00% of Kotlin online submissions for How Many Apples Can You Put into the Basket.