1196. How Many Apples Can You Put into the Basket

LeetCode easy original: C# #array #csharp #easy #hash-table #heap #leetcode #sort
Task text is translated from Russian for the selected interface language. Code is left unchanged.

У вас есть несколько яблок и корзина, которая может выдержать до 5000 единиц веса.

Дан integer array weight, где weight[i] — это вес i-го яблока. return максимальное количество яблок, которые можно положить в корзину.

Example:

Input: weight = [100,200,150,1000]

Output: 4

Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.

C# solution

matched/original
public class Solution {
    public int MaxNumberOfApples(int[] weight) {
        var heap = new SortedSet<int>(weight);
        int apples = 0, units = 0;
        foreach (var w in heap) {
            if (units + w <= 5000) {
                units += w;
                apples++;
            } else {
                break;
            }
        }
        return apples;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int MaxNumberOfApples(vector<int>& weight) {
        var heap = new SortedSet<int>(weight);
        int apples = 0, units = 0;
        foreach (var w in heap) {
            if (units + w <= 5000) {
                units += w;
                apples++;
            } else {
                break;
            }
        }
        return apples;
    }
}

Java solution

matched/original
class Solution {
    public int maxNumberOfApples(int[] arr) {
        List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
        Queue<Integer> heap = new PriorityQueue<>(list);

        int apples = 0, units = 0;

        while (!heap.isEmpty() && units + heap.peek() <= 5000) {
            units += heap.remove();
            apples += 1;
        }
        return apples;
    }
}

JavaScript solution

matched/original
class Solution {
    maxNumberOfApples(weight) {
        weight.sort((a, b) => a - b);
        let apples = 0, units = 0;

        for (const w of weight) {
            if (units + w <= 5000) {
                units += w;
                apples++;
            } else {
                break;
            }
        }
        return apples;
    }
}

Algorithm

Преобразование arrayа в мин-кучу:

Преобразуйте array weight в мин-кучу, чтобы получить минимальные elementы первым.

Инициализация переменных:

Инициализируйте переменные apples для подсчета количества яблок и units для записи текущего веса корзины.

Добавление яблок в корзину:

Пока текущий вес корзины меньше 5000 единиц и в куче остаются elementы:

Увеличивайте apples на 1.

Увеличивайте units на значение, извлеченное из кучи.

😎

Vacancies for this task

Active vacancies with overlapping task tags are shown.

All vacancies
There are no active vacancies yet.