In a movie festival, n movies will be shown. You know the starting and ending times of each movie. What is the maximum number of movies you can watch entirely?
Example:
Input: n = 3, arr = {{3, 5}, {4, 9}, {5, 8}}
Output: 2
Approach
Java
import java.util.Arrays;import java.util.Comparator;public class MovieFestival {public static void main(String[] args) {int n = 3;int[][] arr = { { 3, 5 }, { 4, 9 }, { 5, 8 } };int[][] a = new int[n][2];for (int i = 0; i < n; i++) {int l = arr[i][0];int r = arr[i][1];a[i][0] = r;a[i][1] = l;}System.out.println(movieFestival(n, a));}static int movieFestival(int n, int[][] a) {Arrays.sort(a, Comparator.comparingDouble(o -> o[0]));int ans = 0, pre = -1;for (int i = 0; i < n; i++) {int l = a[i][1];int r = a[i][0];if (l >= pre) {pre = r;ans++;}}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int movieFestival(int n, vector<array<int, 2>> &a){sort(a.begin(), a.end());int ans = 0, pre = -1;for (int i = 0; i < n; i++){int l = a[i][1];int r = a[i][0];if (l >= pre){pre = r;ans++;}}return ans;}int main(){int n = 3;vector<vector<int>> arr = {{3, 5}, {4, 9}, {5, 8}};vector<array<int, 2>> a(n);for (int i = 0; i < n; i++){int l = arr[i][0];int r = arr[i][1];a[i] = {r, l};}cout << movieFestival(n, a) << "\n";return 0;}
No comments:
Post a Comment