|
| 1 | +import UIKit |
| 2 | + |
| 3 | +/* |
| 4 | + # Intuition |
| 5 | + Define a solution space to perform a binary search to find the min # of banans. |
| 6 | + |
| 7 | + # Approach |
| 8 | + Define a range of possible values. We know that the mininum possible value |
| 9 | + is 1 since dividing a number by 0 won't accumulate the sum. The maximum possible |
| 10 | + value is `max(nums)` since any greater than the max will always result in 1. |
| 11 | + Use binary search to half the possible range of answer on each iteration. |
| 12 | + The sum of values increases as the divisor decreases and |
| 13 | + the sum of values decreases as the divisor increases. |
| 14 | + |
| 15 | + Continue reducing the binary search space until it cannot be reduced further. |
| 16 | + |
| 17 | + # Complexity |
| 18 | + - Time complexity: |
| 19 | + O(n log k) |
| 20 | + O(n)(check) * O(log k)(binary search where `k` = `nums.max`) |
| 21 | + |
| 22 | + - Space complexity: |
| 23 | + O(1) only a few integers are stored. |
| 24 | + |
| 25 | + This problem is very similar to Koko eating bananas: https://leetcode.com/problems/koko-eating-bananas/ |
| 26 | + */ |
| 27 | + |
| 28 | +class Solution { |
| 29 | + func check(_ nums: [Int], _ threshold: Int, _ divisor: Int) -> Bool { |
| 30 | + var sum = 0 |
| 31 | + for num in nums { |
| 32 | + sum += Int(ceil(Double(num) / Double(divisor))) |
| 33 | + if sum > threshold { |
| 34 | + return false |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return sum <= threshold |
| 39 | + } |
| 40 | + |
| 41 | + func smallestDivisor(_ nums: [Int], _ threshold: Int) -> Int { |
| 42 | + var l = 1, r = Int.min |
| 43 | + for num in nums { |
| 44 | + r = max(num, r) |
| 45 | + } |
| 46 | + |
| 47 | + while l <= r { |
| 48 | + let mid = (l + r) / 2 |
| 49 | + if check(nums, threshold, mid) { |
| 50 | + // sum <= threshold. Decrease divisor to increase sum. |
| 51 | + r = mid - 1 |
| 52 | + } else { |
| 53 | + // sum > threshold. Increase divisor to decrease sum. |
| 54 | + l = mid + 1 |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return l |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +let res1 = Solution().smallestDivisor([1,2,5,9], 6) // 5 |
| 63 | +let res2 = Solution().smallestDivisor([44,22,33,11,1], 5) // 44 |
0 commit comments