2275. The longest combination of bitwise AND results greater than zero

2275. The longest combination of bitwise AND results greater than zero

Performing a bitwise AND on the array nums is equivalent to performing a bitwise AND on all the integers in the array nums.

例如,对 nums = [1, 5, 3] 来说,按位与等于 1 & 5 & 3 = 1 。
同样,对 nums = [7] 而言,按位与等于 7 。

You are given an array of positive integers candidates. Computes the bitwise AND result of each combination of the numbers in candidates. Each number in candidates can only be used once in each combination.

Returns the length of the longest combination whose bitwise AND result is greater than 0.

Example 1:

Input: candidates = [16,17,71,62,12,24,14]
Output: 4
Explanation: The bitwise AND result of combining [16,17,62,24] is 16 & 17 & 62 & 24 = 16 > 0.
The combined length is 4.
It can be proved that there is no combination of bitwise AND whose result is greater than 0 and whose length is greater than 4.
Note that there may be more than one combination that matches the maximum length.
For example, the bitwise AND result of the combination [62,12,24,14] is 62 & 12 & 24 & 14 = 8 > 0 .

Example 2:

Input: candidates = [8,8]
Output: 2
Explanation: The longest combination is [8,8], and the bitwise AND result is 8 & 8 = 8 > 0.
The combined length is 2, so 2 is returned.

I feel like the questions I’ve done recently don’t have any algorithms, they’re all very skill-based. The code to solve this question is as follows:



int largestCombination(int* candidates, int candidatesSize){
    
    
    int count[32];
    for(int i=0;i<32;i++){
    
    
        count[i]=0;
    }
    int max=0;
    for(int i=0;i<candidatesSize;i++){
    
    
        int ta=candidates[i];
        int p=1;
        int index=0;
        while(ta){
    
    
            if(ta&p){
    
    
                count[index]++;

            }
            index++;
            ta=ta>>1;

        }
    }
    for(int i=0;i<32;i++){
    
    
        max=fmax(max,count[i]);
    }
    return max;
}

Guess you like

Origin blog.csdn.net/weixin_43327597/article/details/133269910