class Solution:
def flipLights(self, n: int, presses: int) -> int:
if presses == 0:
return 1
if n == 1:
return 2
if n == 2:
return 3 if presses == 1 else 4
if presses == 1:
return 4
if presses == 2:
return 7
return 8
class Solution {
public:
int flipLights(int n, int presses) {
if (presses == 0) return 1;
if (n == 1) return 2;
if (n == 2) return presses == 1 ? 3 : 4;
if (presses == 1) return 4;
if (presses == 2) return 7;
return 8;
}
};
class Solution {
public int flipLights(int n, int presses) {
if (presses == 0) return 1;
if (n == 1) return 2;
if (n == 2) return presses == 1 ? 3 : 4;
if (presses == 1) return 4;
if (presses == 2) return 7;
return 8;
}
}
var flipLights = function(n, presses) {
if (presses === 0) return 1;
if (n === 1) return 2;
if (n === 2) return presses === 1 ? 3 : 4;
if (presses === 1) return 4;
if (presses === 2) return 7;
return 8;
};
You are given n
bulbs, all initially turned on. There are four different switches that can flip the bulbs in the following ways:
Each switch can be pressed any number of times, but you can press a total of at most presses
times in any order (even pressing the same switch more than once).
Your task is to return the number of different possible statuses (on/off configurations) of the bulbs after performing at most presses
operations. Each bulb is either on or off.
Constraints:
n
≤ 1000presses
≤ 1000
At first glance, it might seem that there are a huge number of possible states, especially with large n
and presses
. Brute-forcing all possible press sequences is impractical. However, by analyzing the nature of the switches and how they interact, we can see that:
This leads us to consider combinations of switch presses rather than sequences, and also to realize that for n > 6
, the number of unique states does not increase.
n
is.
k
presses where k
≤ presses
and k
has the same parity as presses
(since extra presses can be wasted by pressing the same switch twice).
n
and presses
, the number of possible states is less than 8. Hardcode these for efficiency.
In practice, the number of unique states is:
presses == 0
n == 1
and presses > 0
n == 2
n >= 3
depending on presses
Let's take n = 3
and presses = 1
as an example:
For n = 2
and presses = 1
:
presses
.
The solution is extremely efficient due to the combinatorial reduction and symmetry in the problem.
The key insight is that the number of unique bulb configurations is limited by the patterns of the switches, not by the size of n
or presses
. By analyzing the toggling effects and using combinatorics, we reduce the problem to a handful of cases. This makes the solution both elegant and highly efficient, suitable for even the largest constraints.