Maximum Sum of Non-Adjacent Elements
Updated
Problem statement
Choose any number of elements from the integer array nums so that no two chosen indices are consecutive.
Return the maximum possible sum. You may choose no elements; that choice has sum 0. There is no fixed selection count.
Function
maxNonAdjacentSum(nums: int[]) → longExamples
Example 1
nums = [2,7,9,3,1]return = 12Choose indices 0, 2 and 4: 2 + 9 + 1 = 12.
Example 2
nums = [-4,-2,-9]return = 0Choosing no elements gives 0, which is greater than every nonempty allowed sum.
Example 3
nums = []return = 0The empty array permits only the empty selection.
Constraints
- 0 <= nums.length <= 100000.
- -1000000000 <= nums[i] <= 1000000000.