How to successfully erase multiple characters from a string in inner loop !!
The expression i = max(-1LL, i - 2); is used to adjust the index i after removing two characters from the string and ensure that i does not become less than -1. Here’s what each part means:
Breakdown:
i - 2:- After erasing two characters from the string at position
i, we move the index back by 2 to account for the removed characters. - This is necessary because, after removing characters, we need to re-check the new characters that come into the current and previous positions.
- After erasing two characters from the string at position
-1LL:- This represents the value
-1as a long long data type (LLsuffix means "long long"). - The use of
-1here is to ensure that after the adjustment, the indexidoesn't become negative and out of bounds for the loop. Specifically, if we subtract 2 from a very low index (likei = 0ori = 1),i - 2would result in a negative value like-1or lower. - By limiting
ito-1at most, we prevent potential issues with indexing (e.g., accessing an invalid string position).
- This represents the value
max(-1LL, i - 2):- The
maxfunction returns the larger of the two values:-1LLandi - 2. - This ensures that
inever goes below-1. Ifi - 2is less than-1, it will return-1, otherwise, it will returni - 2.
- The
Why Use max(-1LL, i - 2):
- After erasing two characters, we move the index back to ensure we don't miss checking new adjacent characters.
- The
maxensures thatidoes not go out of bounds, particularly wheniis close to the beginning of the string. Ifigoes below-1, it might cause invalid indexing in subsequent iterations.
Example:
Suppose i = 1 before erasing two characters:
i - 2would be-1.- The
max(-1LL, -1)returns-1. - This ensures that
iis not set to a value lower than-1, which could potentially cause errors.
In this case, setting i = -1 means that the next iteration will set i = 0 (since i++ happens at the end of the loop), so no character is skipped.
This is mainly a safeguard to prevent i from going negative in a way that would break the program.
If you want to delete 3 chars then it will be i = max(-1ll,i-3)
Comments
Post a Comment