C# same as others: greater of 2 passes.


  • 0
    public int Rob(int[] nums) {
        if (nums.Length == 1) return nums[0];
        int v1 = Rob(nums, 0, nums.Length - 1);
        int v2 = Rob(nums, 1, nums.Length - 1);
        return v1 > v2 ? v1 : v2;
    }
    
    public int Rob(int[] nums, int start, int length) {
        if (length <= 0) return 0;
        if (length == 1) return nums[start + 0];
        int p2 = nums[start + 0];
        int p1 = nums[start + 1] > nums[start + 0] ? nums[start + 1] : nums[start + 0];
        int max = p1;
        
        for (int i = start + 2; i < start + length; i++)
        {
            int curr = nums[i] + p2 > p1 ? nums[i] + p2 : p1;
            p2 = p1;
            p1 = curr;
            max = curr > max ? curr : max;
        }
        return max;
    }

Log in to reply
 

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