Record brushing questions-(leetcode-198 house robbery)

Subject: You are a professional thief, planning to steal houses along the street. There is a certain amount of cash hidden in each room. The only restrictive factor that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by a thief at the same night, the system will automatically alarm .
Given an array of non-negative integers representing the amount of money stored in each house, calculate the maximum amount that can be stolen in one night without touching the alarm device.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Steal house 1 (amount = 1), then steal house 3 (amount = 3).
The highest amount stolen = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Steal house 1 (amount = 2), steal house 3 (amount = 9), then steal house 5 (amount = 1 ).
The highest amount stolen = 2 + 9 + 1 = 12.
Source: LeetCode
Link: https://leetcode-cn.com/problems/house-robber
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: dynamic programming
code:

int rob(int* nums, int numsSize){
    
    
    int dp[numsSize+1];
    if(numsSize==0)
        return 0;
    dp[0]=nums[0];
    if(numsSize>1)
    dp[1]=nums[0]>nums[1]?nums[0]:nums[1];
    for(int i=2;i<numsSize;i++){
    
    
        int temp1=dp[i-2]+nums[i];
        int temp2=dp[i-1];
        dp[i]=temp1>temp2?temp1:temp2;
    }
    return dp[numsSize-1];
}

Insert picture description here

Guess you like

Origin blog.csdn.net/lthahaha/article/details/106428799