Maximum Sum of Non-adjacent Elements in 1D array

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

    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.

提交回复
热议问题