Leetcode[594] Longest Harmonious Sequence

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • -10^9 <= nums[i] <= 10^9

Difficulty

  • Level: Easy
  • Acceptance: 51.2%

Solution

Time Complexity: O(n), Space Complexity: O(n)

Analysis

For this question, I used a map just for the fun of it. Using an object would work as well. The first for loop will loop through the array and store each number as a key along with the number of times they are repeated. The second for loop will check for a number in the array and a number that is one greater than it. If both numbers can be found in the map, the algorithm checks to see if the sum of their number of occurrences exceed max. If the sum exceed max, replace it with the sum else, continue with looping through the array.

I have a passion for coding.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store