LeetCode 题解工作台

最大或值

给你一个下标从 0 开始长度为 n 的整数数组 nums 和一个整数 k 。每一次操作中,你可以选择一个数并将它乘 2 。 你最多可以进行 k 次操作,请你返回 nums[0] | nums[1] | ... | nums[n - 1] 的最大值。 a | b 表示两个整数 a 和 b 的 按位或 …

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们注意到,为了使得答案最大,我们应该将 次乘 作用于同一个数。 我们先预处理出数组 的后缀或值数组 ,其中 表示 $nums[i], nums[i + 1], \cdots, nums[n - 1]$ 的按位或值。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始长度为 n 的整数数组 nums 和一个整数 k 。每一次操作中,你可以选择一个数并将它乘 2 。

你最多可以进行 k 次操作,请你返回 nums[0] | nums[1] | ... | nums[n - 1] 的最大值。

a | b 表示两个整数 a 和 b 的 按位或 运算。

 

示例 1:

输入:nums = [12,9], k = 1
输出:30
解释:如果我们对下标为 1 的元素进行操作,新的数组为 [12,18] 。此时得到最优答案为 12 和 18 的按位或运算的结果,也就是 30 。

示例 2:

输入:nums = [8,1,2], k = 2
输出:35
解释:如果我们对下标 0 处的元素进行操作,得到新数组 [32,1,2] 。此时得到最优答案为 32|1|2 = 35 。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 15
lightbulb

解题思路

方法一:贪心 + 预处理

我们注意到,为了使得答案最大,我们应该将 kk 次乘 22 作用于同一个数。

我们先预处理出数组 numsnums 的后缀或值数组 sufsuf,其中 suf[i]suf[i] 表示 nums[i],nums[i+1],,nums[n1]nums[i], nums[i + 1], \cdots, nums[n - 1] 的按位或值。

接下来,我们从左到右遍历数组 numsnums,同时维护当前的前缀或值 prepre。对于当前遍历到的位置 ii,我们将 nums[i]nums[i]22kk 次方,即 nums[i]×2knums[i] \times 2^k,与 prepre 进行按位或运算,得到的结果再与 suf[i+1]suf[i + 1] 进行按位或运算,即可得到以 nums[i]nums[i] 为最后一个数的最大或值。枚举所有的 ii,即可得到答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def maximumOr(self, nums: List[int], k: int) -> int:
        n = len(nums)
        suf = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            suf[i] = suf[i + 1] | nums[i]
        ans = pre = 0
        for i, x in enumerate(nums):
            ans = max(ans, pre | (x << k) | suf[i + 1])
            pre |= x
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate should demonstrate understanding of bitwise operations and greedy algorithms.

  • question_mark

    Look for efficient handling of the k operations on a single element to maximize OR.

  • question_mark

    Candidate may struggle if they fail to prioritize which element to operate on.

warning

常见陷阱

外企场景
  • error

    Failing to apply all k operations on a single element, leading to suboptimal OR values.

  • error

    Not recognizing the importance of bitwise OR and how each operation doubles the value of an element.

  • error

    Inefficient brute-force approaches that involve recalculating the OR too often.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allowing operations on multiple elements, not just one.

  • arrow_right_alt

    Changing the type of operation (e.g., multiplying by a factor other than 2).

  • arrow_right_alt

    Considering a scenario where the OR operation also involves other bit manipulations (e.g., XOR).

help

常见问题

外企场景

最大或值题解:贪心·invariant | LeetCode #2680 中等