Require assistance in locating the longest coherent array in which the gap between the highest and lowest values is precisely one

I am facing a challenge with the following situation: rather than just displaying the length of an array, I want to output the actual array itself.

In this scenario, we are defining a harmonious array as one where the difference between its maximum and minimum values is exactly 1. The task at hand is to find the length of the longest harmonious subsequence within an integer array, focusing on actually identifying the array itself.

For instance: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence in this case would be [3,2,2,2,3].

I have attempted to solve this issue through coding, but it seems that the values being added into 'vals' are incorrect. Any guidance or correction would be greatly appreciated.

const findLHS = (nums) => {
    const hash = new Map()
    let vals = []
    let min = nums[0], max = nums[0]
    for (let num of nums) {
        // Flawed logic for finding min and max values
        min = min + max === 1 ? Math.min(min, num) : min
        max = max - min === 1 ? Math.max(max, num) : max
        hash.set(num, (hash.get(num) || 0) + 1)
        console.log(max);
    }

    // Issue in logic below
    for (let key of nums) {
        if (hash.has(key) === min || hash.has(key) === max) {
            vals.push(min) || vals.push(max)
        }
    }
    return vals
}

The test cases, along with my expected results:

console.log(findLHS([1, 3, 2, 2, 5, 2, 3, 7]))//5 [3,2,2,2,3]
console.log(findLHS([1, 2, 3, 4])) //2 [1,2]
console.log(findLHS([1, 2, 2, 1])) //4 [1,2,2,1]

Answer №1

Let's break it down using the array [1, 3, 2, 2, 5, 2, 3, 7] as an example...

  • Step 1: Create a Map to keep track of the frequency of each value. For instance, 1=>1, 3=>2, 2=>3, 5=>1, 7=>1
  • Step 2: Identify the maximum total count between two consecutive values. For example, there are 4 occurrences when transitioning from 1's to 2's (1x1 + 3x2). Moving on, between 2's and 3's, there are 5 occurrences (3x2 + 2x3). Continue this process.
  • Step 3: Traverse through the original array and extract the values based on the calculated totals. If we determine that there are 5 combined occurrences of 2's and 3's, search for those values in the array.

function findLHS( arr ) {

  // Calculate the frequency of each value in the array...
  let count = new Map();
  arr.forEach( v => {
    count.set( v, ( count.get( v ) || 0 ) + 1 );
  } );
  
  // Determine the largest sum of counts between two sequential numbers.
  let maxKey;
  let maxCount = -1;
  count.forEach( ( val, key ) => {
    if ( count.get( key + 1 ) ) {
      let total = val + count.get( key + 1 );
      if ( maxCount < total ) {
        maxKey = key;
        maxCount = total;
      }
    }
  } );
  
  // Return the final result.
  if ( maxCount == -1 ) {
    return [];
  } 
  
  return arr.reduce( ( acc, val) => {
    if ( val == maxKey || val == maxKey + 1 ) {
      acc.push( val );
    }
    return acc
  }, [] );
    
}

console.log( findLHS( [ 1, 3, 2, 2, 5, 2, 3, 7] ) ); 
console.log( findLHS( [ 1, 2, 3, 4] ) );
console.log( findLHS( [ 1, 2, 2, 1 ] ) );

I trust this explanation is clear and beneficial...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

Discover the current style being applied using JavaScript

After taking a look at this particular post on Stack Overflow about How to retrieve the background color of an element using javascript? I discovered that by using div.style.color You can access the color applied to the div element. However, it seems ...

Tips for storing multiple pieces of text in HTML5 local storage

I have been working on creating functions and input boxes within a table to display data upon page reload. However, I am encountering difficulties in understanding how to store multiple inputs in local storage and then loop through them to show all the d ...

ajax is unable to decode a JSON string from a GET request

Currently, I am leveraging angularjs to retrieve userId, userTitle, and userComment from a form. These values are then sent to a PHP page from the controller for communication with a server. Everything works well when sending integers, but I face an issue ...

What is the Best Method for Filtering an HTML Table Efficiently?

Currently, I have an ajax function that calls a servlet to retrieve a list of products from multiple web services. This list can potentially contain up to 100,000 items and needs to be displayed in an HTML table. In order to provide users with a filtering ...

Having difficulty in successfully transmitting a dictionary via AJAX (POST) to Python (Django views) resulting in an empty dictionary every time

When I include this script in the head of the HTML : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> and then use a button to call a function: <div> ...

What is the best way to incorporate new elements into the DOM in order to allow users to share their comments

Can anyone help me with the code below? I have a text box and a comment section, along with a button to add comments. However, I need assistance with adding the posted comment below the comment section. Below is the code snippet: <div id="comments"&g ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Using a conditional statement in a JavaScript loop

Here is the data I have: companyList: [ { company_name: 'company1', item: 'item1' }, { company_name: 'company1', item: 'item2' }, { company_n ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

When you try to create a popover, a cautionary message pops up indicating that $tooltip is no longer supported. It is

I need help with creating a popover that appears when hovering over an anchor tag. Here is the code I am using: angular: 1.4.2 ui-bootstrap :0.14.2 <div class="row" ng-repeat="endorsement in endorsements| filter: {category:categorySelected}"> &l ...

Customizing the returned data in Jquery autocomplete

I have the following code snippet: $(document).ready(function () { if ($('#au').length <= 0) { return; } var $project = $('#au'); $project.autocomplete({ minLength: 4, source: function (reque ...

"Exploring the Relationship Between Pointers and Arrays in the C Programming

While I wouldn't call myself an expert in the C language, I thought I had a good understanding of pointers until I encountered two different implementations that supposedly produce the same result. I can't seem to wrap my head around it. Can some ...

Is it possible to verify the presence of an ID with jQuery?

Is it possible to check for the existence of the id 'input-name' before assigning a value to the variable name using a line of code similar to this: var name = $('#input-name').attr("value"); In case the id 'input-name' does ...

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

The React Bootstrap modal fails to display the value of an argument passed through a parameter

I am currently working on a project that utilizes React for its front end development. Below is the code snippet: import React, {useState} from 'react'; import Tree from 'react-d3-tree'; import { useCenteredTree } from "./helpers&q ...

Manually load a node.js module from scratch

Is there a way to utilize Node's native "module" module for manually loading in a module from a file instead of relying on the normal require function? I understand this may seem like an unusual request, but I specifically need modules that declare t ...

The functionality of Body Parser has been phased out

I'm facing an issue with using Bodyparser in my code as the editor itself cuts off the code and mentions that body-parser is deprecated. I've attempted to use some alternative codes found online, but none of them seem to be working. Here's a ...

A method for retrieving individual elements of an array from user input and subsequently transferring them to a function in a separate C file

Struggling to figure out how to retrieve each element of an array from user input and then passing it to a function in another file? If so, I could use some help with my code. Here's what I have so far: main.c #include <stdio.h> #include "lab8 ...