leetcode - 2939. Maximum Xor Product

Description

Given three integers a, b, and n, return the maximum value of (a XOR x) * (b XOR x) where 0 <= x < 2n.

Since the answer may be too large, return it modulo 10^9 + 7.

Note that XOR is the bitwise XOR operation.

Example 1:

复制代码
Input: a = 12, b = 5, n = 4
Output: 98
Explanation: For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98. 
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Example 2:

复制代码
Input: a = 6, b = 7 , n = 5
Output: 930
Explanation: For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.
It can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Example 3:

复制代码
Input: a = 1, b = 6, n = 3
Output: 12
Explanation: For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.
It can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.

Constraints:

复制代码
0 <= a, b < 2^50
0 <= n <= 50

Solution

Solved after help.

Try every bit, if a * b < (a ^ bit) * (b ^ bit), then use bit to change the current bit.

Time complexity: o ( m i n ( log ⁡ a , log ⁡ b , n ) ) o(min(\log a, \log b, n)) o(min(loga,logb,n))

Space complexity: o ( 1 ) o(1) o(1)

Code

python3 复制代码
class Solution:
    def maximumXorProduct(self, a: int, b: int, n: int) -> int:
        bit = 1
        while bit < (1 << n):
            if a * b < (a ^ bit) * (b ^ bit):
                a ^= bit
                b ^= bit
            bit <<= 1
        return (a * b) % 1000000007
相关推荐
MrZhao40010 分钟前
Agent 长上下文处理机制:Context Compact 与 Memory 的协同
算法
要开心吖ZSH11 分钟前
处方物流信息同步优化:从 36 秒到亚秒级的踩坑记录
java·数据库·mysql·性能优化
Wang's Blog13 分钟前
JavaWeb快速入门: MyBatis入门与实战
java·mybatis
h_a_o777oah19 分钟前
【动态规划】区间 DP :三层循环逻辑与模板实现细节(洛谷 P1880)
c++·算法·动态规划·acm·区间dp·化环为链·石子合并
从此以后自律24 分钟前
迪杰斯特拉
算法
EntyIU27 分钟前
Java NIO 实战
java·开发语言·nio
二宝哥28 分钟前
springboot项目使用Gradle工具实现依赖版本控制
java·spring boot·后端·gradle·版本
QiLinkOS32 分钟前
第三视觉理解徐玉生与他的商业活动(32)
大数据·c++·人工智能·算法·开源协议
KaMeidebaby43 分钟前
卡梅德生物技术快报|实操手册:CXCL4 蛋白原核表达全套工艺,两步层析去除蛋白多聚体附完整电泳数据
人工智能·算法·机器学习·架构·spark
济*沧*海1 小时前
Set集合深度解析:原理、特性与应用场景全攻略
java