[leetcode] 3

1 minute read

LeetCode 1431 Kids With the Greatest Number of Candies

Problem

Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies.

해석

주어진 Array candies candies[i] 는 i가 갖고 있는 candies의 숫자를 값으로 갖고 있다.candies[i]의 value가 extraCandies를 추가한 후에 candies[]안의 Max값과 같거나 이상이 되면 true를 그렇지 않다면 false를 갖는 result를 보내주면 된다.

Solution in JavaScript

var kidsWithCandies = function (candies, extraCandies) {
  var result = [];
  for (var j = 0; j < candies.length; j++) {
    if (candies[j] + extraCandies < Math.max.apply(null, candies)) {
      //candies[]에 Math.max함수를 쓰기위해서  apply메소드를 활용 하여
      //candies[]을 가져왔다. call()은 하나씩 가져오기 때문에 apply활용

      result.push(false);
    } else {
      result.push(true);
    }
  }
  return result;
};

Solution in Java

class Solution {
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        List<Boolean> result = new ArrayList<>();
 // Arrays.sort(candies); 잘못된 활용
        int max = candies[0];
        for(int j=0;j<candies.length;j++){
            if(candies[j]>max)
                max=candies[j];
        }
        for(int i:candies){
            if(i+extraCandies>=max){
                result.add(true);
            }else
                result.add(false);

        }
        return result;
    }
}

JavaScript처럼 Math.max를 활용하면 좋을 거라고 생각했지만 찾지를 못하였다. 그래서 Arrays.sort()를 활용하여 candies[]를 정렬한후에 마지막 값을 max로 하여 활용하려 하였다.
하지만 Arrays.sort(candies)을 활용하면 정렬이 되기때문에 index의 값이 무시가 된다. 그래서 for문을 활용하여 max값을 찾았다.

Updated: