Skip to content

2505. Bitwise OR of All Subsequence Sums

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  long long subsequenceSumOr(vector<int>& nums) {
    long ans = 0;
    long prefix = 0;

    for (const int num : nums) {
      prefix += num;
      ans |= num | prefix;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public long subsequenceSumOr(int[] nums) {
    long ans = 0;
    long prefix = 0;

    for (final int num : nums) {
      prefix += num;
      ans |= num | prefix;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def subsequenceSumOr(self, nums: list[int]) -> int:
    ans = 0
    prefix = 0

    for num in nums:
      prefix += num
      ans |= num | prefix

    return ans