# Greedy Algorithm Problem Solutions in LeetCodeAnimation: 4 Classic Examples Explained

> Explore greedy algorithm problem solutions for four classic LeetCode problems with animations in C++, Java, and Python. Master Sort Colors, Stock Profit, and Majority Element.

- Repository: [吴师兄学算法/LeetCodeAnimation](https://github.com/MisterBooo/LeetCodeAnimation)
- Tags: tutorial
- Published: 2026-03-01

---

**The LeetCodeAnimation repository contains greedy algorithm problem solutions for four classic LeetCode problems—Sort Colors, Best Time to Buy and Sell Stock, Best Time to Buy and Sell Stock II, and Majority Element—implemented in C++, Java, and Python with detailed animations and explanations.**

The `MisterBooo/LeetCodeAnimation` repository is widely recognized for visualizing algorithmic concepts. Within its `notes/` directory, you will find specific markdown files dedicated to **greedy algorithm problem solutions** that break down complex logic into step-by-step animations and multilingual code implementations.

## Overview of Greedy Algorithm Solutions in the Repository

The repository focuses on four specific problems where the greedy choice property applies—making locally optimal decisions at each step leads to a globally optimal solution. Each solution is documented in a dedicated markdown file within the `notes/` directory, containing algorithmic explanations, complexity analysis, and reference implementations.

## Detailed Breakdown of Each Greedy Problem Solution

### 1. Sort Colors (LeetCode 75) – Dutch National Flag

The **Sort Colors** solution implements the Dutch National Flag algorithm using a single-pass three-pointer partition. This approach greedily places each encountered element into its correct partition (0, 1, or 2) without backtracking.

The greedy nature lies in the immediate decision-making: when encountering a `0`, it is swapped to the front; when encountering a `2`, it is swapped to the back; `1`s are left in place. This "replace-as-you-go" strategy ensures the array is sorted in **O(n)** time with **O(1)** space.

Source file: `notes/LeetCode第75号问题：颜色分类.md`

```cpp
void sortColors(vector<int> &nums) {
    int zero = -1;          // [0…zero] == 0
    int two  = nums.size(); // [two…n‑1] == 2
    for (int i = 0; i < two; ) {
        if (nums[i] == 1) {
            ++i;
        } else if (nums[i] == 2) {
            --two;
            swap(nums[i], nums[two]);
        } else { // nums[i] == 0
            ++zero;
            swap(nums[zero], nums[i]);
            ++i;
        }
    }
}

```

### 2. Best Time to Buy and Sell Stock (LeetCode 121) – Single Transaction

This solution employs a greedy "keep the best so far" method. The algorithm scans the price array once, maintaining the minimum price encountered to date and calculating the potential profit if sold at the current price.

The greedy choice is to always retain the lowest buying price seen so far, ensuring that any future higher price yields the maximum possible profit from that historical minimum. This approach runs in **O(n)** time with **O(1)** space.

Source file: `notes/LeetCode第121号问题：买卖股票的最佳时机.md`

### 3. Best Time to Buy and Sell Stock II (LeetCode 122) – Unlimited Transactions

Unlike the single-transaction variant, this solution allows unlimited buying and selling. The greedy strategy here accumulates profit from every upward price movement. Whenever today's price exceeds yesterday's, the difference is added to the total profit.

This works because unlimited transactions allow the algorithm to capture all positive daily returns without penalty. The greedy choice—taking every local increase—synthesizes into the global maximum profit. Complexity remains **O(n)** time and **O(1)** space.

Source file: `notes/LeetCode第122号问题：买卖股票的最佳时机II.md`

```java
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }
}

```

### 4. Majority Element (LeetCode 169) – Boyer-Moore Voting

The **Boyer-Moore Voting Algorithm** solves the Majority Element problem through a greedy elimination process. The algorithm maintains a candidate element and a counter. When encountering the same element, the counter increments; when encountering a different element, the counter decrements.

The greedy aspect is the immediate discarding of pairs of different elements. If the counter reaches zero, a new candidate is selected. Because the majority element appears more than `n/2` times, it survives the elimination process. This runs in **O(n)** time with **O(1)** space.

Source file: `notes/LeetCode第169号问题：求众数.md`

```java
class Solution {
    public int majorityElement(int[] nums) {
        int candidate = nums[0], count = 1;
        for (int i = 1; i < nums.length; ++i) {
            if (count == 0) {
                candidate = nums[i];
                count = 1;
            } else if (nums[i] == candidate) {
                ++count;
            } else {
                --count;
            }
        }
        return candidate;
    }
}

```

## Summary

- The **LeetCodeAnimation** repository contains four documented **greedy algorithm problem solutions** located in the `notes/` directory.
- **Sort Colors (75)** uses a three-pointer Dutch National Flag partition for **O(n)** in-place sorting.
- **Best Time to Buy and Sell Stock (121)** applies a greedy minimum-tracking strategy for single-transaction maximum profit.
- **Best Time to Buy and Sell Stock II (122)** accumulates all positive daily price differences using unlimited transaction greediness.
- **Majority Element (169)** implements Boyer-Moore voting, greedily eliminating non-majority pairs to find the dominant element in **O(1)** space.

## Frequently Asked Questions

### What languages are used for the greedy algorithm implementations?

The repository provides implementations in **C++**, **Java**, and **Python**. The markdown notes in the `notes/` directory contain code snippets in these languages, with some problems showing multiple language implementations for comparison.

### Where can I find the animation explanations for these greedy solutions?

Each solution is documented in a dedicated markdown file within the `notes/` directory. For example, `notes/LeetCode第75号问题：颜色分类.md` contains the animated explanation for Sort Colors. These files combine algorithmic descriptions with visual illustrations to demonstrate how the greedy choices progress step-by-step.

### Why is the Boyer-Moore voting algorithm considered greedy?

The **Boyer-Moore** algorithm for Majority Element is greedy because it makes an immediate local decision to discard pairs of different elements whenever they are encountered. It maintains a candidate and eliminates non-matching elements without reconsidering previous choices, ensuring that if a majority element exists, it will survive the elimination process. This "eliminate on sight" strategy is the hallmark of a greedy approach.

### Does the repository include greedy solutions for other LeetCode problems?

Currently, the repository specifically documents four classic greedy algorithm solutions as detailed above. While the repository contains many other algorithmic animations, these four problems represent the core **greedy algorithm problem solutions** explicitly categorized and explained with animations in the `notes/` directory.