Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created July 31, 2020 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/91aef7f3b8512b5752e9f8cd01583816 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/91aef7f3b8512b5752e9f8cd01583816 to your computer and use it in GitHub Desktop.
Leetcode #1529: Bulb Switcher IV (https://www.InterviewRecipes.com/leetcode-1529)
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