Maximum Sum of Non-adjacent Elements in 1D array

后端 未结 4 521
小蘑菇
小蘑菇 2021-01-27 09:30

Given an array of integers, find a maximum sum of non-adjacent elements. For example, inputs [1, 0, 3, 9, 2,-1] should return 10 (1 + 9).

4条回答
  •  太阳男子
    2021-01-27 10:02

    You search for the maximum value M1 in linear time.

    You search for the second non-adjacent maximum value M2 in linesr time.

    S1 = M1 + M2

    If M1 is the first or the last element, the answer is S1.

    Otherwise you add the two values adjacent to M1:

    S2 = A1 + A2

    The solution is then max(S1, S2)

    Ok, ShreePool is interested concretely in S1. For other people who might be interested, the only other possible pair of non-adjacent elements which could have a bigger sum are precisely A1 and A2, as if one of them wasn't, it wouldn't be adjacent to M1 and it would have been a candidate for S1.

    Now, to find M1 and M2 in linear time, there are several options. I write one which requires only one pass.

    Precondition: size >= 3;
    function nonAdjacentMaxPair(a: Integer [], size: Integer): Integer [] is
       var first: Integer;
       var second: Integer;
       var third: Integer;
       var maxs: Integer [2];
       var i: Integer;
       first := 0;
       second := 1;
       third := 2;
       if (A [1] > A [0]) then
          first := 1;
          second := 0;
       endif;
       if (A [2] > A [1]) then
          third := second;
          second := 2;
          if (A [2] > A [0]) then
             second := first;
             first := 2;
          endif;
       endif;
       i := 3;
       while (i < size) do
          if (A [i] > A [third]) then
             third := i;
             if (A [i] > A [second]) then
                third := second;
                second := i;
                if(A [i] > A [first]) then
                   second := first;
                   first := i;
                endif;
             endif;
          endif;
          i := i + 1;
       endwhile;
       maxs [0] := first;
       maxs [1] := second;
       if (second = first + 1 or second = first - 1) then
          maxs [1] := third;
       endif;
       return maxs;
    endfunction;
    

    And S1 is A [maxs [0]] + A [maxs [1]]

    Hope this is what you needed.

    For the record: A1 + A2 is A [maxs [0] - 1] + A [maxs [0] + 1], if maxs [0] is neither 0 nor size.

提交回复
热议问题