C/Golang without a 'max and one 'if'


  • 0
    M

    We can use simple operations to either increment the current count or reset it back to 0 as follows cur = (cur + elem) * elem. However, the multiplication can simplified to cur = (cur + elem) & -elem where:

    • elem = 1 -> -elem = 1..1
    • elem = 0 -> -elem = 0

    Anding the above results with cur + elem will then either increment or 0 cur.

    Corresponding C code:

    int findMaxConsecutiveOnes(int* nums, int numsSize) {
        int cur = 0, max = 0;
        for (int i = 0; i < numsSize; i++)
            if ((cur = (cur + nums[i]) & -nums[i]) > max)
                max = cur;
        return max;
    }
    

    Corresponding Go code

    func findMaxConsecutiveOnes(nums []int) int {
        cur, max := 0, 0
        for _, n := range(nums) {
            cur = (cur + n) & -n
            if cur > max {
                max = cur
            }
        }
        
        return max
    }
    

Log in to reply
 

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