Advertisement
amitsen01ei

Greedy.java

Oct 2nd, 2023
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | Source Code | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Greedy {
  4.  
  5.     /**
  6.      * Given a set of intervals, finds the length of the maximal set of mutually
  7.      * disjoint intervals. Two intervals are considered disjoint if they don't
  8.      * have any point in common.
  9.      *
  10.      * <p>Time complexity: O(N * log(N)) where N is the number of intervals.
  11.      * This is because the main computational effort is spent on sorting the intervals.
  12.      * After sorting, the algorithm performs a single pass through the list.
  13.      *
  14.      * <p>Space complexity: O(1) as no additional space (proportional to the input size)
  15.      * is used beyond the input list of intervals. However, the sorting itself in Java
  16.      * might require O(N) space due to the characteristics of the sorting algorithm
  17.      * employed by the Arrays.sort() method in the List interface that uses Tim Sort.
  18.      *
  19.      * @param matrix The list of intervals, where each interval is represented as a list with
  20.      *          two integers denoting the start and end of the interval.
  21.      * @return The length of the maximal set of mutually disjoint intervals.
  22.      *
  23.      */
  24.     public static int maxDisjointIntervals(ArrayList<ArrayList<Integer>> matrix) {
  25.  
  26.         matrix.sort(Greedy::comparing);
  27.  
  28.         var count = 1;
  29.         var lastEnd = matrix.get(0).get(1);
  30.  
  31.         for (var r : matrix) {
  32.             if (r.get(0) > lastEnd) {
  33.                 count++;
  34.                 lastEnd = r.get(1);
  35.             }
  36.         }
  37.         return count;
  38.     }
  39.  
  40.     private static int comparing(ArrayList<Integer> a, ArrayList<Integer> b) {
  41.         return a.get(1).equals(b.get(1)) ? Integer.compare(a.get(0), b.get(0)) :
  42.                 Integer.compare(a.get(1), b.get(1));
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement