โ† Back to Index

๐Ÿ“š Greedy Techniques โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Greedy Technique is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most immediate benefit. It is used for optimization problems where local choices lead to a globally optimal solution.

๐Ÿงฑ Pattern Template

Greedy Algorithm

class Solution {
    public int findMaxProfit(int[] tasks) {
        Arrays.sort(tasks); // Sort tasks based on a specific criterion
        int profit = 0;

        for (int task : tasks) {
            if (isFeasible(task)) { // Check if the task can be included
                profit += task;
            }
        }

        return profit;
    }

    private boolean isFeasible(int task) {
        // Implement feasibility check logic
        return true;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Coin Change Problem

Input: coins = [1, 2, 5], amount = 11
Output: 3

Explanation:
- Use coins [5, 5, 1] to make up the amount 11 with the minimum number of coins.

๐Ÿ’ก Pro Tips