menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

3397. Maxi...
source image

Medium

2d

read

221

img
dot

3397. Maximum Number of Distinct Elements After Operations | Leetcode |Medium.

  • The problem can be solved using two approaches:
  • Brute Force approach: Sort the array in ascending order and create a set for unique elements. Loop through the array and for each element, check if NUMS[i]-K and NUMS[i]+K are not present in the set. If not present, add them to the set. Return the size of the set for the maximum number of distinct elements.
  • Time complexity: O(n*log(n) + n*k)
  • Greedy approach: Sort the array in ascending order. Initialize a minimum value as INT_MIN. Loop through each element in the array and calculate the start value as max(minimum, NUMS[i]-K). If start ≤ NUMS[i]+K, increment the count. Update the minimum value to start + 1. Return the count for the maximum number of distinct elements.
  • Time complexity: O(n*log(n) + n)

Read Full Article

like

13 Likes

For uninterrupted reading, download the app