View on GitHub

SCRATCH PAD

No polish, just pulse

Striver’s SDE Sheet Notes (Day 8: Greedy Algorithm)


1. N Meetings in One Room

  public int maxMeetings(int start[], int end[], int n) {
      int count = 1;
      int lastEnd = end[0];
      for (int i = 1; i < n; i++) {
          if (start[i] > lastEnd) {
              count++;
              lastEnd = end[i];
          }
      }
      return count;
  }
  

2. Minimum Number of Platforms Required for a Railway

  public int findPlatform(int[] arr, int[] dep, int n) {
      Arrays.sort(arr);
      Arrays.sort(dep);
      int platforms = 1, result = 1;
      int i = 1, j = 0;
      while (i < n && j < n) {
          if (arr[i] <= dep[j]) {
              platforms++;
              i++;
          } else {
              platforms--;
              j++;
          }
          result = Math.max(result, platforms);
      }
      return result;
  }
  

3. Job Sequencing Problem

  public int jobScheduling(Job[] jobs, int n) {
      Arrays.sort(jobs, (a, b) -> b.profit - a.profit);
      int[] result = new int[n];
      Arrays.fill(result, -1);
      int maxProfit = 0;
      for (int i = 0; i < n; i++) {
          for (int j = Math.min(n, jobs[i].deadline) - 1; j >= 0; j--) {
              if (result[j] == -1) {
                  result[j] = i;
                  maxProfit += jobs[i].profit;
                  break;
              }
          }
      }
      return maxProfit;
  }
  

4. Fractional Knapsack Problem

  public double fractionalKnapsack(int W, Item arr[], int n) {
      Arrays.sort(arr, (a, b) -> Double.compare(b.value / (double) b.weight, a.value / (double) a.weight));
      double maxValue = 0.0;
      for (int i = 0; i < n; i++) {
          if (W >= arr[i].weight) {
              W -= arr[i].weight;
              maxValue += arr[i].value;
          } else {
              maxValue += arr[i].value * (W / (double) arr[i].weight);
              break;
          }
      }
      return maxValue;
  }
  

5. Greedy Algorithm to Find Minimum Number of Coins

  public int minCoins(int[] coins, int V) {
      Arrays.sort(coins);
      int count = 0;
      for (int i = coins.length - 1; i >= 0; i--) {
          if (V >= coins[i]) {
              count += V / coins[i];
              V %= coins[i];
          }
      }
      return count;
  }
  

6. Assign Cookies

  public int findContentChildren(int[] g, int[] s) {
      Arrays.sort(g);
      Arrays.sort(s);
      int i = 0, j = 0, count = 0;
      while (i < g.length && j < s.length) {
          if (g[i] <= s[j]) {
              count++;
              i++;
          }
          j++;
      }
      return count;
  }