Longest Harmonious Subsequence

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
subsequence of the array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

Example 1:

Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Approach

Java


import java.util.HashMap;

public class HLS {
    public static void main(String[] args) {
        int[] nums = { 13225237 };
        System.out.println(findLHS(nums));
    }

    static int findLHS(int[] nums) {
        int ans = 0;
        HashMap<IntegerIntegerump = new HashMap<IntegerInteger>();

        // count frequency of each elements
        for (int i : nums) {
            ump.put(i, ump.getOrDefault(i, 0) + 1);
        }

        // iterate for all elements
        for (Integer i : ump.keySet()) {
            int a = ump.getOrDefault(i - 10);
            int b = ump.getOrDefault(i + 10);
            if (a > 0 || b > 0)
                ans = Math.max(ans, ump.get(i) + Math.max(a, b));
        }
        return ans;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int findLHS(vector<int&nums)
{
    int ans = 0;
    unordered_map<intintump;

    //count frequency of each elements
    for (int i : nums)
    {
        ump[i]++;
    }

    //iterate for all elements
    for (int i = 0i < nums.size(); i++)
    {
        int a = ump[nums[i] - 1];
        int b = ump[nums[i] + 1];
        if (a > 0 || b > 0)
            ans = max(ansump[nums[i]] + max(ab));
    }
    return ans;
}
int main()
{
    vector<intnums = {13225237};
    cout << findLHS(nums);
    return 0;
}


No comments:

Post a Comment