Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1221greedy
You work on a monitoring system. Every minute it records a health check as P for passed or F for failed, so a day is a string such as PPFFPF.
A stretch is balanced when it holds as many passes as fails. The whole day is balanced. Your team lead asks: "Cut the day into consecutive pieces so that every piece is balanced, and make as many pieces as you can."
Write most_balanced_pieces(checks).
checks is a string of P and F. It holds the same number of each.P as F.Input: checks = "PPFFPF"
Output: 2Keep a balance: add 1 for each P and take 1 away for each F. Each time it returns to 0, the part since the last cut is balanced, so cut there.
| Character | Balance | Cut here? | Pieces |
|---|---|---|---|
| P | 1 | no | 0 |
| P | 2 | no | 0 |
| F | 1 | no | 0 |
| F | 0 | yes | 1 |
| P | 1 | no | 1 |
| F | 0 | yes | 2 |
The pieces are PPFF and PF, so the answer is 2.
Input: checks = "PFPFPF"
Output: 3The balance is back to 0 after every second character: three pieces of PF.
Input: checks = "PPPFFF"
Output: 1The balance reaches 0 only at the end, so the whole string is one piece.
2 ≤ len(checks) ≤ 100,000checks holds only P and F, with the same number of eachThe string can have 100,000 characters. Choosing where to cut means choosing a subset of 99,999 places, which is 2^99999 ways. One pass that keeps a single number costs 100,000 steps and needs no sort.