1431. Kids with the greatest number of candies
#LeetCode_75
There aren
kids with candies. You are given an integer arraycandies
, where eachcandies[i]
represents the number of candies theith
kid has, and an integerextraCandies
, denoting the number of extra candies that you have.
Return a boolean arrayresult
of lengthn
, whereresult[i]
istrue
if, after giving theith
kid all theextraCandies
, they will have the greatest number of candies among all the kids, orfalse
otherwise.
Note that multiple kids can have the greatest number of candies.
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
python
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
n = len(candies)
result = []
temp_candies = candies.copy()
for i in range(n):
temp_candies[i] = candies[i] + extraCandies
if temp_candies[i] == max(temp_candies):
result.append(True)
else:
result.append(False)
temp_candies = candies.copy()
return result
I solved this problem with the idea that the the origin list is left and the copied list changes according to the for loop proceed. And the result list[boolean] is extend as the loop proceeds.
javascript
var kidsWithCandies = function(candies, extraCandies) {
const n = candies.length;
let result = [];
// Find the maximum number of candies any child has
const maxCandies = Math.max(...candies);
for (let i = 0; i < n; i++) {
// Check if the current child has the greatest number of candies
// after receiving the extra candies
result.push((candies[i] + extraCandies) >= maxCandies);
}
return result;
};
This is optimized code by chatgpt4. There are several points optimized.
Math.max(...candies)
is called once before the loop to find the maximum number of candies any child has.- Inside the loop, we simply check if each child's candies plus
extraCandies
is greater than or equal tomaxCandies
. - We use
push
to add eithertrue
orfalse
to theresult
array based on this condition.
java
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int n = candies.length;
List<Boolean> result = new ArrayList<>();
int maxCandies = Arrays.stream(candies).max().orElse(Integer.MIN_VALUE);
for (int i=0; i<n; i++){
result.add((candies[i] + extraCandies) >= maxCandies);
}
return result;
}
}
- In java there is certain difference between
array
andList
. You can't just doCollections.max();
for
array and List of Java
- Array
- array is a fixed length of iterable collection.
- array's length can't be changed.
int[]
- List
- Interface
ArrayList
,LinkedList
- length of list can be changed.
add
remove
Collections.max
can be applied to a List not a array. Arrays.asList
method can be easy way to do this. But this method is not appliable to a Basic type array. So it would be recommanded to just use stream API in this situation.
import java.util.Arrays;
int maxCandies = Arrays.stream(candies).max().orElse(Integer.MIN_VALUE);
Stream?
Java Streams, introduced in Java 8, provide a new way of processing collections of data in a declarative manner. A stream represents a sequence of elements and supports different kinds of operations to perform computations on those elements.
- Stream Creation:
You can create a stream from various data sources, such as collections or arrays, using methods likeArrays.stream()
,Collection.stream()
, orStream.of()
. - Intermediate Operations:
These operations transform a stream into another stream. They are lazy, meaning they don't start processing the content until a terminal operation is invoked. Examples includefilter
,map
,sorted
, etc. - Terminal Operations:
These operations produce a result or a side-effect from processing the elements of the stream. Once a terminal operation is performed, the stream pipeline is considered consumed, and no further operations can be performed on it. Examples includeforEach
,collect
,reduce
,max
,min
, etc.
import java.util.Arrays;
int maxCandies = Arrays.stream(candies).max().orElse(Integer.MIN_VALUE);
In this example, the goal is to find the maximum value in an array of candies:
Arrays.stream(candies)
: This part of the code creates a stream from thecandies
array..max()
: This is a terminal operation on the stream that finds the maximum element. It returns anOptionalInt
because the maximum element may or may not exist (e.g., the stream could be empty)..orElse(Integer.MIN_VALUE)
: This method is called on theOptionalInt
returned bymax()
. If theOptionalInt
has a value, it returns that value. If not, it returnsInteger.MIN_VALUE
as a default value. This is useful for providing a fallback value in case the stream is empty, and no maximum value exists.
Using Java Streams allows for more concise and readable data processing. It supports a functional programming style and offers advanced features like parallel processing. Streams greatly enhance readability and maintainability of the code, especially when dealing with complex data manipulation tasks.