diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 195140b4..f8207684 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -113,6 +113,7 @@ | 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy | | 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy | | 1207 | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [C](./src/1207.c) | Easy | +| 1283 | [Find the Smallest Divisor Given a Threshold]https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/description/) | [C](./src/1283.c) | Medium | | 1695 | [Maximum Erasure Value](https://leetcode.com/problems/maximum-erasure-value/) | [C](./src/1695.c) | Medium | | 1769 | [Minimum Number of Operations to Move All Balls to Each Box](https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/) | [C](./src/1769.c) | Medium | | 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium | diff --git a/leetcode/src/1283.c b/leetcode/src/1283.c new file mode 100644 index 00000000..ccdf9e29 --- /dev/null +++ b/leetcode/src/1283.c @@ -0,0 +1,44 @@ +#define max(a,b) (((a)>(b))?(a):(b)) + +long getSum(int* nums, int numsSize, int divizor){ + long result = 0; + for (int i = 0; i < numsSize; i++){ + int value = nums[i] / divizor; + if (value * divizor != nums[i]){ + value++; + } + + result += value; + } + + return result; +} + +// Divide and conquer +// Runtime: O(n*log(n)) +// Space: O(1) +int smallestDivisor(int* nums, int numsSize, int threshold){ + int maxNum = 0; + for (int i = 0; i < numsSize; i++){ + maxNum = max(maxNum, nums[i]); + } + + int left = 1; + int right = maxNum; + while (left <= right){ + int middle = (left + right) / 2; + long middleSum = getSum(nums, numsSize, middle); + if (middleSum <= threshold && (middle == 1 || getSum(nums, numsSize, middle - 1) > threshold)){ + return middle; + } + + if (middleSum > threshold){ + left = middle + 1; + } + else{ + right = middle - 1; + } + } + + return -1; +}