C++ O(n) one dimension dp array


  • 0
    C
    class Solution {
    public:
        int rob(vector<int> &num) {
    
    			if (num.size() == 0)
    				return 0;
    			else if (num.size() == 1)
    				return num[0];
            
    			vector<int> cash(num.size(), 0);			    			
    			for (int i = 0; i < num.size(); i++) {
    
    				int prev1 = 0;
    				if (i >= 3)
    					prev1 = cash[i - 3];
    
    				int prev2 = 0;
    				if (i >= 2)
    					prev2 = cash[i - 2];
    
    				cash[i] = max(prev1, prev2) + num[i];
    			}
    			
    			return max(cash[num.size() - 1], cash[num.size() - 2]);
        }
    };

Log in to reply
 

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