Here is the link to the contest.
A. Valid Parentheses
The most optimal length is achieved if no parentheses need to be removed, but sometimes parentheses must be removed to maintain the balanced property. This happens when encountering a ) before a matching (. To solve this, traverse the string from left to right. Every time you encounter a (, increment the open parentheses count by one. If you encounter a ), the count of open parentheses must be at least one. If it is, decrement the count by one and increment your result by two (one for the ( and one for the ) because both are part of the remaining valid string). If not, it means you have to remove this closing parenthesis.
def solve():
s = input()
result = opened = 0
for ch in s:
if ch == '(':
opened += 1
elif opened:
result += 2
opened -= 1
print(result)
if __name__ == "__main__":
solve()
B. Chef Jamie
Given a list where removing one element can result in a sorted array:
- The out-of-order elements form a nearly sorted sequence.
- It takes ( K — 1 ) swaps to sort ( K ) out-of-order elements, as each swap fixes one element's position, and the last swap finalizes the sorting.
Example
Consider the list: [1, 2, 3, 7, 4, 5, 6, 9, 10]
.
- The out-of-order elements are
[7, 4, 5, 6]
because they are not in the correct positions. - To correct this, we need 3 swaps.
Here's how we can sort it with swaps:
- Initial Array:
[1, 2, 3, 7, 4, 5, 6, 9, 10]
- Swap
7
and4
:[1, 2, 3, 4, 7, 5, 6, 9, 10]
- Swap
7
and5
:[1, 2, 3, 4, 5, 7, 6, 9, 10]
- Swap
7
and6
:[1, 2, 3, 4, 5, 6, 7, 9, 10]
We needed 3 swaps to sort the array, which is ( K — 1 ) where ( K = 4 ) (the number of out-of-order elements).
Generally, by comparing this list with the sorted version, we can identify the out-of-order sequence by counting the mismatches.
def solve():
n = int(input())
arr = list(map(int, input().split()))
ordered = sorted(arr)
swaps = 0
for i in range(n):
swaps += arr[i] != ordered[i]
print(max(0, swaps - 1))
if __name__ == "__main__":
solve()
C. Experiment
What will be the brute force solution? The brute force solution is to determine the maximum number of rooms required at any given moment, from the earliest start time to the time when all experiments are completed.
Try to use prefix sum (sweep line) to optimize the brute force solution.
def solve():
D. Minimum Park Lighting Cost
To solve this problem we have to use stack
def solve():
E. Secure The Castle
To solve this problem we have to use stack
def solve():