Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenTASTEWINMDateiverwaltungEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichInvestierenTASTESTOCKDesktop-App für automatischen AktienhandelErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpackenTASTEWINMEin tastaturorientierter Dateimanager mit zwei Fenstern

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Investieren

TASTESTOCKAutomatischer Aktienhandel nach Ihren Regeln: wann und was

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienÜber unsDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
Gestern
Aufrufe gesamt
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

Greedy-Algorithmen-Dokumentation
Greedy-Algorithmen
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Diskussionen

Greedy-Algorithmen-Anleitung · 5/6

Practice Problems

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

Most greedy problems fall apart the moment you find the right ordering. The four problems below each exercise a different greedy rule. Before reading a solution, pick your rule and try to justify it in one sentence.

Problem 1. Choosing inspection times

Each sensor in a plant has a time window [l, r] (both ends inclusive) in which its reading must be checked. An inspector does a round at chosen moments and checks every sensor whose window contains that moment. Find the fewest rounds that check every sensor, and their times.

Approach: sort windows by end time. The earliest-ending unchecked window must be inspected by its end anyway, so placing the round as late as possible, at r, covers the most later windows. As an exchange argument: moving the first round of an optimal plan to r never uncovers a window.

def min_check_times(windows):
    times = []
    for l, r in sorted(windows, key=lambda w: w[1]):
        if not times or times[-1] < l:  # last round happened before this window
            times.append(r)
    return times


print(min_check_times([(1, 4), (2, 6), (5, 8), (7, 9), (10, 12)]))  # [4, 8, 12]

Problem 2. Loading spices (fractional knapsack)

A cart carries at most W kg. Each spice has a total value and weight, and you may scoop any portion of it. Find the maximum value you can load.

Approach: load spices in order of value per kilogram. When a spice is heavier than the remaining capacity, take just enough to fill the cart and stop. Swapping some expensive spice for a cheaper one can only lose value, so the rule is optimal. For exact results use fractions.Fraction, or compare ratios by cross-multiplication instead of division.

def max_cart_value(items, capacity):
    """items: list of (value, weight)."""
    total = 0.0
    for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
        if capacity <= 0:
            break
        take = min(weight, capacity)
        total += value * take / weight
        capacity -= take
    return total


print(max_cart_value([(120, 3), (100, 5), (60, 4)], 10))  # 250.0

If items cannot be split (0/1 knapsack) this rule is wrong. With (60, 10), (100, 20), (120, 30) and capacity 50, ratio-greedy gets 160 while the optimum is 220.

Problem 3. Tasks finished before their deadlines

Each task has a duration and a deadline, and you process one task at a time without breaks, starting at time 0. Maximize the number of tasks finished on time (late tasks are simply not done).

Approach: accept tasks in order of deadline, and whenever the running time overshoots the current deadline, drop the longest task accepted so far. Dropping the longest keeps the count the same while freeing the most time for later tasks. You need a max-heap, so store negated durations in Python.

Fragen zu diesem Kapitel?
Vorheriges KapitelComplexityNächstes KapitelReal-World Use
import heapq


def max_on_time(tasks):
    """tasks: list of (duration, deadline)."""
    heap, time = [], 0
    for duration, deadline in sorted(tasks, key=lambda t: t[1]):
        heapq.heappush(heap, -duration)
        time += duration
        if time > deadline:
            time += heapq.heappop(heap)  # negative, so this subtracts the longest duration
    return len(heap)


print(max_on_time([(3, 4), (2, 5), (4, 7), (1, 8), (3, 9)]))  # 4

Problem 4. Cheapest way to merge files

You want to merge n files of different sizes into one. Merging two files costs the sum of their sizes. Find the minimum total cost.

Approach: each file's size is paid once for every merge it takes part in (its depth in the merge tree), so this is exactly Huffman coding. Always merge the two smallest files.

import heapq


def min_merge_cost(sizes):
    heap = list(sizes)
    heapq.heapify(heap)
    cost = 0
    while len(heap) > 1:
        a = heapq.heappop(heap)
        b = heapq.heappop(heap)
        cost += a + b
        heapq.heappush(heap, a + b)
    return cost


print(min_merge_cost([4, 3, 2, 6]))  # 29

Merging left to right (4+3, 7+2, 9+6) costs 7 + 9 + 15 = 31, while greedy does 2+3, 4+5, 6+9 for 5 + 9 + 15 = 29.

Check yourself

  • Write a small randomized test that compares each solution against brute force. Inputs of size 6 to 8 finish instantly.
  • In problem 1, how does the comparison change if the windows are half-open?
  • In problem 3, does dropping the task you just added (instead of the longest) admit a counterexample?

Summary

  • Inspection times: sort by end, place a point at the end of each uncovered window.
  • Fractional knapsack: sort by value per weight, split only the last item.
  • Deadlines: add by deadline, and on overflow drop the longest task from a heap.
  • File merging: like Huffman, keep merging the two smallest.

0 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.