feat: add Find the Smallest Divisor Given a Threshold (#1175)

* add leetcode Find the Smallest Divisor Given a Threshold

* Update leetcode/DIRECTORY.md

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-21 03:39:35 +04:00 committed by GitHub
parent b819ddf3e6
commit 73913ac4a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View File

@ -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 |

44
leetcode/src/1283.c Normal file
View File

@ -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;
}