Skip to content

Commit c8de25e

Browse files
committed
Adds 1283. Find the Smallest Divisor Given a Threshold
1 parent 3012a11 commit c8de25e

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)