Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 months ago
662 B
2
Indexable
Never
int closestToTarget(std::vector<int> oxygenLevels, int target) {
    int minDiff = std::abs(oxygenLevels[0] - target); // Initialize minimum difference with the first oxygen level
    int current = oxygenLevels[0]; // Initialize current value with the first oxygen level
    
    for (int i = 0; i < oxygenLevels.size(); ++i) {
        current &= oxygenLevels[i]; // Update current value by taking bitwise AND with the next oxygen level
        minDiff = std::min(minDiff, std::abs(current - target)); // Update minimum difference
        if (minDiff == 0) break; // If the difference becomes zero, no need to continue
    }
    
    return minDiff;
}
Leave a Comment