Shree Prakash
Shree Prakash

Reputation: 2314

Maximum Sum of Non-adjacent Elements in 1D array

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).

there should be avoid 3,2 since 9 is adjacent for 3,2. maximum in array + maximum in Non adjacent elements of 9(maximum element in array).

Since maximum element is 9 and next maximum which should be non-adjacent. resulting this 9+1=10(since 1 is maximum in non adjacent element of maximum).

I tried this way in O(n)+O(Max_index-1)+O(Array.length-Max_index+2).

Is there any other way so that I can optimize this code in terms of time complexity.

import java.io.*;
import java.util.*;
//Maximum Sum of Non-adjacent Elements
public class Test{
public static void main(String args[])
{
    int[] a={1, 0, 3, 9, 2,-1,-2,-7};
    int max=a[0];
    int max_index=0;
    for(int i=1;i<a.length;++i)
    {
        if(max<a[i])
        {
            max=a[i];
            max_index=i;
        }
    }
    int m1=a[0];
    for(int i=1;i<max_index-1;++i) //get maximum in first half from 0 to max_index-1
    {
        if(m1<a[i])
            m1=a[i];
    }
    int m2=a[max_index+2];
    for(int i=max_index+2;i<a.length;i++)//get maximum in second half max_index+2 to end in array.
    {
        if(a[i]>m2)
        m2=a[i];
    }
    int two_non_adj_max=max+Math.max(m1,m2);
    System.out.println(two_non_adj_max);
}
}

Upvotes: 0

Views: 1473

Answers (4)

SaiSandeep G
SaiSandeep G

Reputation: 11

package abc;

public class Solution {

// int[] A{1,4,5,2,5,4,2}

public int nonAdjacentMaxSumRepeated(int[] inpArray) {

    int[] a = new int[inpArray.length];
    int k=0;
    for(int i=0,j=0;i<inpArray.length;i++) {
        j=i+1; 
        //System.out.println("i="+i);
        //System.out.println("j="+j);
        System.out.println(inpArray[i]+","+inpArray[j]);
        a[k]=inpArray[i]+inpArray[j];k++;
        i=j;
    }
    
    int x=0;
    for (int i : a) {
     x = Math.max(x, i);
    }
    
    return x;
}

public static void main(String[] args) {
    System.out.println(
    new Solution().nonAdjacentMaxSumRepeated(new int[] {1,3,5,2,6,4,2,7})
    );
}

}

Upvotes: 0

Juan
Juan

Reputation: 430

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.

Upvotes: 1

Matt Timmermans
Matt Timmermans

Reputation: 59144

Let BEST_SUM(i) be the maximum sum of non-adjacent elements at positions <= i.

When i<0,   BEST_SUM(i) = 0
Otherwise:  BEST_SUM(i) = max( BEST_SUM(i-1), BEST_SUM(i-2)+a[i] )

BEST_SUM(a.length-1) is your answer.

NOTE: This is the max sum of non-adjacent elements, like you asked for. Looking at your code it looks like you may mean the best sum of two non-adjacent elements. The would be different, and easier.

Upvotes: 1

clemens
clemens

Reputation: 17711

As far as I understand your problem:

int max = Integer.MIN_VALUE;

for(int i = 0; i < a.length - 2; ++i) {
    for(int j = i + 2; j < a.length; ++j) {
        max = Math.max(max, a[i] + a[j]);
    }
}

This algorithm has complexity of O(n ²).

Sketch for a faster algorithm: You could sort the array values with its indices in descending order. Than you can search for the highest pair which has non-adjacent indices. This algorithm takes O(n log n) steps.

Upvotes: 0

Related Questions