|
| 1 | +// Source : https://leetcode.com/problems/bulb-switcher-iv/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-03-29 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * There is a room with n bulbs, numbered from 0 to n-1, arranged in a row from left to right. |
| 8 | + * Initially all the bulbs are turned off. |
| 9 | + * |
| 10 | + * Your task is to obtain the configuration represented by target where target[i] is '1' if the i-th |
| 11 | + * bulb is turned on and is '0' if it is turned off. |
| 12 | + * |
| 13 | + * You have a switch to flip the state of the bulb, a flip operation is defined as follows: |
| 14 | + * |
| 15 | + * Choose any bulb (index i) of your current configuration. |
| 16 | + * Flip each bulb from index i to n-1. |
| 17 | + * |
| 18 | + * When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0. |
| 19 | + * |
| 20 | + * Return the minimum number of flips required to form target. |
| 21 | + * |
| 22 | + * Example 1: |
| 23 | + * |
| 24 | + * Input: target = "10111" |
| 25 | + * Output: 3 |
| 26 | + * Explanation: Initial configuration "00000". |
| 27 | + * flip from the third bulb: "00000" -> "00111" |
| 28 | + * flip from the first bulb: "00111" -> "11000" |
| 29 | + * flip from the second bulb: "11000" -> "10111" |
| 30 | + * We need at least 3 flip operations to form target. |
| 31 | + * |
| 32 | + * Example 2: |
| 33 | + * |
| 34 | + * Input: target = "101" |
| 35 | + * Output: 3 |
| 36 | + * Explanation: "000" -> "111" -> "100" -> "101". |
| 37 | + * |
| 38 | + * Example 3: |
| 39 | + * |
| 40 | + * Input: target = "00000" |
| 41 | + * Output: 0 |
| 42 | + * |
| 43 | + * Example 4: |
| 44 | + * |
| 45 | + * Input: target = "001011101" |
| 46 | + * Output: 5 |
| 47 | + * |
| 48 | + * Constraints: |
| 49 | + * |
| 50 | + * 1 <= target.length <= 10^5 |
| 51 | + * target[i] == '0' or target[i] == '1' |
| 52 | + ******************************************************************************************************/ |
| 53 | + |
| 54 | +class Solution { |
| 55 | +public: |
| 56 | + int minFlips(string target) { |
| 57 | + //flip the target to initalization |
| 58 | + int flip = 0; |
| 59 | + for(auto state : target) { |
| 60 | + if (state == '0' && flip % 2 == 1 ) flip++; |
| 61 | + if (state == '1' && flip % 2 == 0 ) flip++; |
| 62 | + } |
| 63 | + return flip; |
| 64 | + } |
| 65 | +}; |
0 commit comments