You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>Let $f(n)$ represent the probability that the $n$th passenger will sit in their own seat when there are $n$ passengers boarding. Consider from the simplest case:</p>
79370
-
<ul>
79371
-
<li>
79372
79370
<p>When $n=1$, there is only 1 passenger and 1 seat, so the first passenger can only sit in the first seat, $f(1)=1$;</p>
79373
-
</li>
79374
-
<li>
79375
79371
<p>When $n=2$, there are 2 seats, each seat has a probability of 0.5 to be chosen by the first passenger. After the first passenger chooses a seat, the second passenger can only choose the remaining seat, so the second passenger has a probability of 0.5 to sit in their own seat, $f(2)=0.5$.</p>
79376
-
</li>
79377
-
</ul>
79378
79372
<p>When $n>2$, how to calculate the value of $f(n)$? Consider the seat chosen by the first passenger, there are three cases.</p>
<p>We note that if the string <code>croakOfFrogs</code> is composed of several valid <code>"croak"</code> characters mixed together, its length must be a multiple of $5$. Therefore, if the length of the string is not a multiple of $5$, we can directly return $-1$.</p>
79367
+
<p>Next, we map the letters <code>'c'</code>, <code>'r'</code>, <code>'o'</code>, <code>'a'</code>, <code>'k'</code> to indices $0$ to $4$, respectively, and use an array $cnt$ of length $5$ to record the number of occurrences of each letter in the string <code>croakOfFrogs</code>, where $cnt[i]$ represents the number of occurrences of the letter at index $i$. Additionally, we define an integer variable $x$ to represent the number of frogs that have not completed their croak, and the minimum number of frogs needed $ans$ is the maximum value of $x$.</p>
79368
+
<p>We traverse each letter $c$ in the string <code>croakOfFrogs</code>, find the index $i$ corresponding to $c$, and then increment $cnt[i]$ by $1$. Next, depending on the value of $i$, we perform the following operations:</p>
79369
+
<ul>
79370
+
<li>If $i=0$, then a new frog starts croaking, so we increment $x$ by $1$, and then update $ans = \max(ans, x)$;</li>
79371
+
<li>Otherwise, if $cnt[i-1]=0$, it means that there is no frog that can make the sound $c$, and the croak cannot be completed, so we return $-1$. Otherwise, we decrement $cnt[i-1]$ by $1$. If $i=4$, it means that a frog has completed a croak, so we decrement $x$ by $1$.</li>
79372
+
</ul>
79373
+
<p>After traversing, if $x=0$, it means that all frogs have completed their croaks, and we return $ans$. Otherwise, we return $-1$.</p>
79374
+
<p>The time complexity is $O(n)$, and the space complexity is $O(C)$. Where $n$ is the length of the string <code>croakOfFrogs</code>, and $C$ is the size of the character set, in this problem $C=26$.</p>
0 commit comments