-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_1283.java
63 lines (52 loc) · 1.41 KB
/
leetcode_1283.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// 1283. Find the Smallest Divisor Given a Threshold
// Brute force approach
class Solution {
public int smallestDivisor(int[] nums,int threshold) {
int count = 1;
while(true) {
int sum = 0;
for(int num: nums) {
sum += Math.ceil((double) num / (double) count)
}
if(sum == threshold) {
return count;
}
count++;
}
return count;
}
}
// Optimal approach
class Solution {
// function to find the largest element in an array
public int largest(int[] nums) {
int elem = nums[0];
for(int num : nums) {
if(num > elem) {
elem = num;
}
}
return elem;
}
// function to find the sum of ceil values of the elements till n
public int sumIndex(int[] nums,int n) {
int sum = 0;
for(int num : nums) {
sum += (int) Math.ceil((double)num/(double)n);
}
return sum;
}
public int smallestDivisor(int[] nums, int threshold) {
int minimum = 1;
int maximum = largest(nums);
while(minimum <= maximum) {
int mid = ( minimum + maximum )/2;
if(sumIndex(nums,mid) <= threshold) {
maximum = mid - 1;
} else {
minimum = mid + 1;
}
}
return minimum;
}
}