Maximum Sum of Non-adjacent Elements in 1D array

后端 未结 4 515
小蘑菇
小蘑菇 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:09

    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.

提交回复
热议问题