当前位置:网站首页>1646. Recursive method of getting the maximum value in the generated array

1646. Recursive method of getting the maximum value in the generated array

2022-07-23 09:12:00 Mr Gao

1646. Get the maximum value in the generated array

Give you an integer n . According to the following rules to generate a length of n + 1 Array of nums :

nums[0] = 0
nums[1] = 1
 When  2 <= 2 * i <= n  when ,nums[2 * i] = nums[i]
 When  2 <= 2 * i + 1 <= n  when ,nums[2 * i + 1] = nums[i] + nums[i + 1]

Returns the generated array nums Medium Maximum value .

Example 1:

Input :n = 7
Output :3
explain : According to rules :
nums[0] = 0
nums[1] = 1
nums[(1 * 2) = 2] = nums[1] = 1
nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2
nums[(2 * 2) = 4] = nums[2] = 1
nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3
nums[(3 * 2) = 6] = nums[3] = 2
nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3
therefore ,nums = [0,1,1,2,1,3,2,3], Maximum 3

Example 2:

Input :n = 2
Output :1
explain : According to rules ,nums[0]、nums[1] and nums[2] The maximum of these is 1

Example 3:

Input :n = 3
Output :2
explain : According to rules ,nums[0]、nums[1]、nums[2] and nums[3] The maximum of these is 2

Add a little skill to this question , The solution code is as follows :

int f(n){
    
     if(n==1){
    
        return 1;
    }
    if(n==0){
    
        return 0;
    }
     if(n%2==0){
    
        return f(n/2);
    }
    else{
    
        return f(n/2)+f(n/2+1);
    }

}


int getMaximumGenerated(int n){
    
    if(n==1){
    
        return 1;
    }
    if(n==0){
    
        return 0;
    }
    if(n==2){
    
        return 1; 
    }
    int max=0;
    for(int i=3;i<=n;i=i+2){
    
     // printf("%d %d",i,f(i));
        if(f(i)>max){
    
            max=f(i);
        }
    }
     //printf(" %d ",max);
return max;   

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230045575543.html