Advertisement
MiinaMagdy

Untitled

Nov 25th, 2022 (edited)
710
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. int pickCoupons(int n, vector<int> &coupons)            //  2 Pointers Solution
  3. {
  4.     int l = 0;
  5.     unordered_map<int, int> mp;
  6.     int ans = INT_MAX;
  7.     for (int r = 0; r < n; r++) { // using map for sliding window
  8.         mp[coupons[r]]++;
  9.         while (mp[coupons[r]] > 1) {
  10.     /*     
  11.             once the occurrence of coupons[r] > 1 this means there are more than 1 of the same coupon
  12.             then we will check the answer
  13.             and remove the left side till the occurrence return to 1 : mp[coupons[r]] == 1
  14.     */
  15.             ans = min(ans, r - l + 1);
  16.             mp[coupons[l]]--;
  17.             l++;
  18.         }
  19.     }
  20.     return (ans == INT_MAX ? -1 : ans);
  21. }
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement