1431. Kids with the greatest number of candies

1431. Kids with the greatest number of candies

#LeetCode_75

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

 

💡
Examples 1:

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.

💡
Note that the list needs to be copied with List.copy() method. If you just copy with it, the copied list change as the origin list change.

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 to maxCandies.
  • We use push to add either true or false to the result 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;
    }
}
  1. In java there is certain difference between array and List. You can't just do Collections.max(); for

array and List of Java

  1. Array
    1. array is a fixed length of iterable collection.
    2. array's length can't be changed.
    3. int[]
  2. List
    1. Interface
    2. ArrayList, LinkedList
    3. 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.

  1. Stream Creation:
    You can create a stream from various data sources, such as collections or arrays, using methods like Arrays.stream(), Collection.stream(), or Stream.of().
  2. 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 include filter, map, sorted, etc.
  3. 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 include forEach, 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 the candies array.
  • .max(): This is a terminal operation on the stream that finds the maximum element. It returns an OptionalInt 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 the OptionalInt returned by max(). If the OptionalInt has a value, it returns that value. If not, it returns Integer.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.

Read more

airflow 구성하고 vscode로 코딩하기

맥에서 했으면 훨씬 구성이 쉬웠겠지만, 그리고 poetry로 했으면 훨씬 쉬웠겠지만 워낙 규모가 있는 라이브러리이다 보니 과정이 어려워 다른 참조들을 보면서 따라했다. 기본적으로 poetry랑 쓰기 어려운 이유는 airflow 내부의 라이브러리에 따라 poetry가 버전을 참조하지 못해서 에러가 나는 경우가 존재한다고 한다. 또한 하나의 문제는 mac에서는 그냥 리눅스가 존재하지만 윈도우에서 하려면 윈도우용 linux인

[Json] dump vs dumps

json은 javascript object notation의 줄임말로 웹 어플리케이션에서 구조화된 데이터를 표현하기 위한 string 기반의 포맷이다. 서버에서 클라인트로 데이터를 전송하여 표현하거나, 그 반대로 클라이언트에서 서버로 보내는 경우들에 사용된다. javascript 객체 문법과 굉장히 유사하지만 워낙에 범용성이 넓게 설계되어 있어서 다른 언어들에도 많이 사용된다. 기본적으로 python 에는 json 이 내장 모듈이다. 바로 import json해주면