Turn all N bulbs off with flips of exactly K consecutive bulbs using the fewest presses, or report Insomnia when it is impossible.
Medium5GreedySliding windowInterviewNo attempts yetTime limit1sMemory limit256 MBAnyone who has spent a night awake knows how painful those hours are. Losing sleep piles up fatigue the next day and wears down daily life, which is why deep sleep is sometimes called a blessing.
Doctor Jammani at Inha University listed a few conditions for sleeping well. The first one is to keep the area around the bed dark.
Junhyeong, who had suffered from severe insomnia, followed that condition and got his health back. Once he was well enough to travel he booked an unusual place to stay, and when he arrived he found that it had very unusual light bulbs.
N bulbs stand in a row, and each bulb is either off or on. Junhyeong wants to turn every bulb off, but there is no switch for an individual bulb. There is only one button, and it inverts the state of exactly K consecutive bulbs at once. Inverting a state turns an off bulb on and an on bulb off.
Junhyeong wants to press the button as few times as possible and still end with every bulb off. Help him by writing a program that reports the minimum number of presses.
Take N=6, K=3, and the states 1 1 0 0 0 1. Inverting bulbs 1 through 3 gives 0 0 1 0 0 1, inverting bulbs 3 through 5 gives 0 0 0 1 1 1, and inverting bulbs 4 through 6 turns every bulb off. No sequence of two or fewer presses clears the row, so the answer here is 3.
The first line contains the number of bulbs N (1≤N≤100,000) and the number of bulbs one press inverts, K (1≤K≤N).
The second line contains N integers S1,S2,…,SN separated by spaces. Si is the state of the ith bulb, where 1 means the bulb is on and 0 means it is off.
Print the minimum number of button presses that turns every bulb off. Note that one press inverts exactly K consecutive bulbs and nothing else.
If no sequence of presses can turn every bulb off, print Insomnia without the quotes.