Maximize sum with no adjacent elements
Company: TikTok
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of dynamic programming and array-based optimization, assessing competency in designing algorithms that maximize a sum under adjacency constraints.
Constraints
- 1 <= n <= 10^5
- 0 <= nums[i] <= 10^9
- Elements are non-negative
- The empty array returns 0
Examples
Input: ([1, 2, 3, 1],)
Expected Output: 4
Explanation: Choose 1 (index 0) and 3 (index 2): 1 + 3 = 4. Choosing 2 and 1 only gives 3.
Input: ([2, 7, 9, 3, 1],)
Expected Output: 12
Explanation: Choose 2 (i0), 9 (i2), 1 (i4): 2 + 9 + 1 = 12.
Hints
- This is the classic 'House Robber' problem. At each index, you either skip the current element or take it (which forbids taking the previous one).
- Track two running values: the best sum that INCLUDES the current element and the best sum that EXCLUDES it. The included value can only build on the previous excluded value.
- You only need the two values from the previous step, so O(1) extra space suffices. Final answer is max(include, exclude).