Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Algoritmi greedy
Algoritmi greedy
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussioni

Guida a Algoritmi greedy · 4/6

Complexity

Per ora questo capitolo è disponibile solo in inglese.

The cost of a greedy algorithm usually comes from sorting or priority-queue operations; the choice itself is often constant time per candidate. That is why the classic greedy algorithms typically run in O(n log n), dropping to O(n) when the input is already sorted.

Complexity by problem

ProblemGreedy ruleTimeExtra space
Interval schedulingearliest endO(n log n)O(n) (sorted copy)
Activity selection (already sorted by end)sameO(n)O(1)
Huffman codingmerge the two lightestO(n log n)O(n)
Huffman (sorted frequencies)two queuesO(n)O(n)
Fractional knapsackhighest value per weightO(n log n)O(n)
Meeting roomsby start + min-heap of endsO(n log n)O(n)

Best, average and worst cases barely differ. Sorting costs O(n log n) regardless of input shape (Python's Timsort drops to O(n) on already sorted data), and the scan that follows is always a single pass. In the meeting-room algorithm the heap never holds more than k entries, the maximum number of simultaneous meetings, so the tighter bound is O(n log k).

Linear-time Huffman with two queues

When frequencies are already sorted ascending, you can compute the Huffman cost with two queues and no heap. Merged weights come out in non-decreasing order, so the second queue stays sorted by itself.

from collections import deque


def huffman_cost_sorted(weights):
    """Total encoded bits for ascending weights, in O(n)."""
    leaves, merged = deque(weights), deque()

    def pop_min():
        if not merged or (leaves and leaves[0] <= merged[0]):
            return leaves.popleft()
        return merged.popleft()

    total = 0
    while len(leaves) + len(merged) > 1:
        a = pop_min()
        b = pop_min()
        total += a + b
        merged.append(a + b)
    return total


print(huffman_cost_sorted([5, 9, 12, 13, 16, 45]))  # 224

Counting rooms without a heap

If you only need the number of rooms, sort start and end times separately and sweep with two pointers. It is still , but with smaller constants and less code. It does not tell you which meeting goes in which room, so use the heap version when you need the assignment.

Domande su questo capitolo?
Capitolo precedenteImplementationCapitolo successivoPractice Problems
O(n log n)
def min_rooms_sweep(meetings):
    starts = sorted(s for s, _ in meetings)
    ends = sorted(e for _, e in meetings)
    rooms = j = 0
    for s in starts:
        if ends[j] <= s:
            j += 1      # inherit the room of a meeting that has ended
        else:
            rooms += 1  # open another room
    return rooms


print(min_rooms_sweep([(9, 10), (9, 12), (10, 11), (11, 13), (12, 13)]))  # 2

Compared with alternatives

ProblemGreedyAlternativeNote
Max number of intervalsoptimal, O(n log n)brute force O(2^n · n)greedy is exact
Weighted intervalsnot optimalDP + binary search O(n log n)greedy fails once values differ
Fractional knapsackoptimal, O(n log n)linear programminggreedy is exact
0/1 knapsacknot optimalDP O(nW)W is the capacity
Change, canonical coinsoptimal, O(k)DP O(k · amount)k coin types
Change, arbitrary coinsnot optimalDP O(k · amount)coins 1, 3, 4

Where greedy is correct it beats the alternatives on both time and memory. But small changes to the problem (adding weights, making items indivisible) take the guarantee away. When the problem changes, re-check correctness before you worry about complexity.

Measure it yourself

You can check the theory against wall-clock time. If time grows a bit more than tenfold when n grows tenfold, that matches O(n log n).

import random
import time


def max_count(intervals):
    count, last_end = 0, float("-inf")
    for start, end in sorted(intervals, key=lambda iv: iv[1]):
        if start >= last_end:
            count, last_end = count + 1, end
    return count


for n in (10_000, 100_000, 1_000_000):
    data = [(s, s + random.randint(1, 100)) for s in (random.randint(0, 10**6) for _ in range(n))]
    t = time.perf_counter()
    max_count(data)
    print(n, f"{time.perf_counter() - t:.3f}s")

Summary

  • Greedy running time is dominated by sorting or heap operations and is usually O(n log n).
  • With pre-sorted input, both activity selection and Huffman coding drop to O(n).
  • Use the two-pointer sweep when you only need a room count, the heap when you need the assignment.
  • Greedy is the fastest option when it is correct, but weights or indivisible items call for dynamic programming.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.