leetcode 198 Dynamic Programming

The meaning of the title is: Given a set of arrays, the sum of the selected sub-arrays (not consecutive) must be maximized, but adjacent ones cannot be selected at the same time.

My thinking: For a[i], either choose or not choose. Assuming that a[i] is selected, then a[i-1] must not be selected, and only the numbers in the first 0~i-2 that can form the largest sum can be seen. This can be considered in this way, define an array sum, sum[i] represents the largest sum of the previous i,

sum[i] = max{sum[i-2]+a[i],a[i-1]}

code show as below

int rob(int* nums, int numsSize) {
    int * sum = (int *)malloc(sizeof(int)*numsSize);
    sum[0] = nums[0];
    sum[1] = nums[1]>nums[0]?nums[1]:nums[0];
    for(int i =2;i<numsSize;i++)
    {
        if(nums[i]+sum[i-2]>sum[i-1])
            sum[i] = nums[i]+sum[i-2];
        else
            sum[i] = sum[i-1];
    }
    return sum[numsSize-1];
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325284004&siteId=291194637