My 15 line c++ code, 0MS runtime for test data.


  • 6
    S
       /************************************
       **  author : s2003zy
       **  blog :  s2003zy.com
       ** weibo:  weibo.com/songzy982
       ****************************************/ 
       class Solution {
        public:
            int res(vector<int>& nums, int left, int right) {
                int last = 0, lastlast = 0;
                for (int i = left; i < right; i++) {
                    lastlast = max(last, lastlast + nums[i]);
                    swap(last, lastlast);
                }
                return last;
            }
            int rob(vector<int>& nums) {
                if (nums.size() == 1) return nums[0];
                return max(res(nums, 0, nums.size() - 1) ,res(nums, 1, nums.size()));
            }
        };

  • 0
    H

    Last line of res function can just be "return last;"


  • 0
    S

    Oh~~~ yes! You are right, thanks a lot


Log in to reply
 

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