Search code examples
phparraysmax

Consolidate array of numbers without exceeding a predefined maximum value per element


I'm trying to combine numbers in an array by adding them so that the max value can only by 30.

For example, this is my array:

array(10,30,10,10,15);

After combining the numbers in the array to items with a max value 30, the result should be:

array(30,30,15);

How to achieve this?


Solution

  • I'm trying to combine numbers in an array by adding them so that the max value can only by 30

    So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:

    • First, sort them.
    • Second, keeping adding elements to sum till you are about to get a sum > 30.
    • Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.

    Code:

    <?php
    
    $arr = array(10,30,10,10,15);
    sort($arr);
    
    $res = [];
    $curr_sum = 0;
    
    foreach($arr as $each_value){
        if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
        else{
            $res[] = $curr_sum;
            $curr_sum = $each_value;
        }
    }
    
    $res[] = $curr_sum;
    
    print_r($res);
    

    Demo: https://3v4l.org/BYhuE

    Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.

    rsort($res);