Created
July 31, 2020 02:16
-
-
Save bhaveshmunot1/91aef7f3b8512b5752e9f8cd01583816 to your computer and use it in GitHub Desktop.
Leetcode #1529: Bulb Switcher IV (https://www.InterviewRecipes.com/leetcode-1529)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
inline char toggle(char c) { | |
return c == '0' ? '1' : '0'; | |
} | |
public: | |
int minFlips(string target) { | |
int n = target.size(); // Total bulbs. | |
int flips = 0; // Final answer. | |
char status = '0'; // This stores the status of bulbs that | |
// are ahead of current index `i`. | |
for (int i=0; i<n; i++) { // For each bulb - | |
if (status != target[i]) { // If what we want is different from what | |
// it is at this moment, make a flip. | |
flips++; // We made a flip. | |
status = toggle(status); // Now status of remaining | |
// bulbs have changed. | |
} | |
} | |
return flips; // Awesome, return the answer now. | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment