Problem statement

https://binarysearch.com/problems/Largest-Sum-of-Non-Adjacent-Numbers/

Solution

Equal to leetcode Leetcode 0198. House Robber

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, nums):
        dp1, dp2 = 0, 0
        for num in nums:
            dp1, dp2 = dp2, max(dp1 + num, dp2)          
        return dp2