1196. How Many Apples Can You Put into the Basket

LeetCode easy original: C# #array #csharp #easy #hash-table #heap #leetcode #sort
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

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

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

Beispiel:

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# Lösung

zugeordnet/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++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 на значение, извлеченное из кучи.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.