Distribute Candies LeetCode
TIME: O(N) [Traversing Array][LeetCode Time : 31ms faster than 86.25%]
SPACE: O(N) [Using HashSet] [LeetCode Memory: 40.5 MB less than 95.93%]
Approach: Using HashSet
HashSet will keep just one occurrence of the element due to which we will clearly get the number of different types of candies available. Then we will compare with the number of chocolates recommended by the doctor. If options available are less than the doctor's recommendation then we will return options else we will return recommend chocolates by a doctor.
class Solution {
public int distributeCandies(int[] arr) {
HashSet<Integer> set=new HashSet<Integer>();
for(int i=0;i<arr.length;i++){
set.add(arr[i]);
}
int a=set.size();//options
int b=arr.length/2;//doctor
if(b>a){
return a;
}
else{
return b;
}
}
}
Thanks for Reading.
"Knowledge grows by sharing not by saving.😇"
Comments
Post a Comment