C solution 0 ms time not very much neat though


  • 0
    A
    void swap(int *x, int *y)
    {
        int t = *x;
        *x = *y;
        *y = t;
    }
    
    int rob(int* nums, int numsSize)
    {
        int curr_max = 0;
        int prev_max = 0;
        int last_broken = 0;
        int i;
        
        if(numsSize == 0)
            return 0;
        if(numsSize == 1)
            return nums[0];
        if(nums[0] >= nums[1])
        {
            curr_max = nums[0];
            last_broken = 0;
        }
        else
        {
            curr_max = nums[1];
            last_broken = 1;
            prev_max = nums[0];
        }
        for(i=2; i<numsSize; i++)
        {
            if(last_broken == i-1)
            {
                if(prev_max+nums[i] > curr_max)
                {
                    swap(&curr_max, &prev_max);
                    curr_max = curr_max + nums[i];
                    last_broken = i;
                }
            }
            else
            {
                prev_max = curr_max;
                curr_max = curr_max + nums[i];
                last_broken = i;
            }
        }
        return curr_max;
    }

Log in to reply
 

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