Problem
Given an integer N
, flip exactly one contiguous segment of bits (from index L
to R
) in its binary representation to maximize the total number of set bits (ones). Return the maximum possible number of ones after performing at most one flip.
Constraints (original):
N
may be large (the original note allowed very large values); practical implementations acceptN
as a standard integer or as a binary string whenN
does not fit in native types.
Example
Example 1
|
|
Solution
We convert the bit-flip problem to a maximum subarray problem (Kadane). Treat each bit b
as a value v
: v = 1
if b == 0
(flipping this 0 gives +1 one), and v = -1
if b == 1
(flipping a 1 reduces the count by 1). The maximum subarray sum of v
gives the best gain in ones achievable by flipping one contiguous segment. Add that gain to the count of existing ones. If all bits are ones (no zeros), the best action is to not flip (gain <= 0), so answer is original number of ones.
Method 1 — Transform + Kadane (optimal)
Intuition
Convert the binary digits to a weight array v
where v[i] = 1
when bit i
is 0
and v[i] = -1
when bit i
is 1
. Flipping a segment adds the sum of v
over that segment to the total number of ones. The best segment is the maximum-sum contiguous subarray of v
(Kadane’s algorithm).
Approach
- Convert
N
to its binary representation (as a vector/list of bits). IfN
is provided as a string, parse that string. - Count
totalOnes =
number of ones in the bit array. - Build array
v
wherev[i] = 1
ifbit[i] == 0
elsev[i] = -1
. - Run Kadane to find
bestGain = max(0, max_subarray_sum(v))
. - Answer =
totalOnes + bestGain
.
Edge cases:
- If there are no zeros,
bestGain
will be<= 0
, so returntotalOnes
(do not flip). - If
N == 0
, flipping the whole bits yields number of bits set equal to number of bits in representation — treat representation carefully (use at least one bit).
Code
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is number of bits — each bit is visited once for conversion and once in Kadane. - 🧺 Space complexity:
O(n)
to store the bit array (can be reduced toO(1)
if bits are streamed and Kadane is run on the fly).