C# solution, O(N) time, O(1) space.


  • 0
    C
     public int Rob(int[] nums) {
                if(nums==null || nums.Length==0)
                {
                    return 0;
                }
    
                if(nums.Length==1)
                {
                    return nums[0];
                }
    
                int sum1 = GetMaxRob(nums, 0, nums.Length - 1);
                int sum2 = GetMaxRob(nums, 1, nums.Length);
    
                return (Math.Max(sum1, sum2));
        }
        
        
            private int GetMaxRob(int[] nums, int startindex, int endindex)
            {
                int a = 0;
                int b = 0;
                bool skip = true;
                for (int i = startindex; i < endindex; i++)
                {
                    if(skip)
                    {
                        a = Math.Max(b, a + nums[i]);
                    }
                    else
                    {
                        b = Math.Max(a, b + nums[i]);
                    }
                    
                    skip = !skip;
                }
    
                return Math.Max(a, b);
            }

Log in to reply
 

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