RainX_69

Find the Maximum Number of Marked Indices | Two Pointers | MUST DO | TRICKY | OA

Apr 14th, 2023 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | Source Code | 0 0
  1. https://leetcode.com/problems/find-the-maximum-number-of-marked-indices/
  2.  
  3. You are given a 0-indexed integer array nums.
  4. Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j.
  5. Return the maximum possible number of marked indices in nums using the above operation any number of times.
  6.  
  7. Example 1:
  8. Input: nums = [3,5,2,4]
  9. Output: 2
  10. Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1.
  11. It can be shown that there's no other valid operation so the answer is 2.
  12.  
  13. Example 2:
  14. Input: nums = [9,2,5,4]
  15. Output: 4
  16. Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0.
  17. In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2.
  18. Since there is no other operation, the answer is 4.
  19.  
  20. Example 3:
  21. Input: nums = [7,6,8]
  22. Output: 0
  23. Explanation: There is no valid operation to do, so the answer is 0.
  24.  
  25. Constraints:
  26. 1 <= nums.length <= 10^5
  27. 1 <= nums[i] <= 10^9
  28. ------------------------------------------------------------------------------------------------------------------
  29.  
  30. class Solution {
  31. public:
  32.    int maxNumOfMarkedIndices(vector<int>& nums) {
  33.        int n=nums.size();
  34.        sort(nums.begin(),nums.end());
  35.        int i=0;
  36.        int j=n/2+n%2;
  37.        int res=0;
  38.        while(j<n){
  39.            if(2*nums[i]<=nums[j]){
  40.                res++;
  41.                i++;
  42.            }
  43.            j++;
  44.        }
  45.        return res*2;
  46.    }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment