C# solution: dp


  • 0
    B
    public class Solution 
    {
        public int Rob(int[] nums) 
        {
            if (nums.Length == 0) return 0;
            if (nums.Length == 1) return nums[0];
            if (nums.Length == 2) return Math.Max(nums[0], nums[1]);
    
            var prePre = nums[0];
            var pre = Math.Max(nums[0], nums[1]);
    
            for (int i = 2; i < nums.Length; i++)
            {
                var cur = Math.Max(prePre + nums[i], pre);
                prePre = pre;
                pre = cur;
            }
    
            return pre;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.