mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
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:
parent
b819ddf3e6
commit
73913ac4a8
@ -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
44
leetcode/src/1283.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user