Sunday, April 17, 2022

LeetCode 2226. Maximum Candies Allocated to K Children

https://leetcode.com/problems/maximum-candies-allocated-to-k-children/

Example 1:

Input: candies = [5,8,6], k = 3
Output: 5
Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.









package pep.Day63;

public class LeetCode_2226_Maximum_Candies_Allocated_to_K_Children {
public static void main(String[] args) {
System.out.println(maximumCandies1(new int[]{4, 7, 5}, 4));
}

public static int maximumCandies1(int[] candies, long k) {
long sum = 0;
for (int x : candies) {
sum += x;
}

long left = 0, right = sum / k;
right++;

long ans = 0;

// = operator is used to perform action when left = right
while (left <= right) {
long mid = (left + right) / 2;

// agr kise bhi bche ko candy dena impossible ho toh 0 return
if (mid == 0)
return 0;

long countPiles = 0;

for (int i = 0; i < candies.length; i++) {
countPiles += (candies[i] / mid);
}

if (countPiles >= k) {
ans = Math.max(ans, mid);
// discard everything from left
left = mid + 1;
} else {
// discard everything from right
right = mid - 1 ;
}

}
return (int) ans;

}

}


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...