Skip to content

1.1 Largest Adjacent Sum

Farrukh Ahmad edited this page Dec 15, 2015 · 1 revision

In this program the given array will in any order, program intension is to make out the largest sum of two neighbour element

if Array is [1,3,4,5,2] the largest sum should be 9 of 4, 5.

Solution:

public class LargestAdjacentSum {

public static void main(String args[]){
    int a[] = {1,5,6,3};
    
    System.out.println(largestAdjacentSum(a));
}

static int largestAdjacentSum(int[ ] a){
    
    if(a.length == 0) return 0;
    if (a.length == 2) return a[0]+a[1];
    
    int largestSum = a[0] + a[1];
    
    for(int i=2; i<a.length -1; i++){
        if(a[i] + a[i+1] > largestSum)
            largestSum = a[i] + a[i+1];
    }
    
    return largestSum;
 } 
}

Clone this wiki locally