Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Split array in three equal sum subarrays

Write a solution for the input array which elements of the array are sorted into three groups. The sum of the elements of each group would should be approximately equal.

Example 1: [7,5,3,1,2,3] Result: [7] // 7, [5,2] //7, [3,3,1] // 7

I managed to do it when there is sum which can be divided in three equal parts. My question is how to upgrade code so it works in cases when sum is not equal or when some element of array is lager than divided sum? Here is my code so far:

    var input=document.getElementById('niz').value;
    var arr=[];
    for (var i = 0; i < input.length; i++) {
        if(input[i]!=" " && !isNaN(input[i])){
            arr.push(input[i]);
        }
        
        
    }
    console.log(arr);
    var n=arr.length;
    var status=true;
    if(n<3){
        status=false;
    }
    else{
        var sum = 0;
        var auxiliary = 0;
        var i=0;
        var j=0;
        //calculate sum of elements
        for(i=0;i<n;i++){
            sum+=arr[i];
        }
        var point = Array(2).fill(0);
        if (sum % 3 == 0)
        {
            // Find that three equal subarray exists in given array
            for (i = 0; i < n && j < 2; ++i)
            {
                // Add current element into auxiliary variable
                auxiliary += arr[i];
                if (auxiliary == parseInt(sum / 3))
                {
                    point[j] = i + 1;
                    // Set zero sum
                    auxiliary = 0;
                    j++;
                }
            }
            if (j == 2)
            {
                // When equal three subarray exist
                j = 0;
                // Print the elements of subarray
                for (i = 0; i < n; ++i)
                {
                    if (j < 2 && point[j] == i)
                    {
                            
                        j++;
                    }
                    
                    console.log(arr[i]);
                }
            }
            else
            {
                status=false;
            }
        }
        else
        {
            status=false;
        }

    }if(status!=true){
        console.log("\n is is not possible")
    }
    
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!