The person from PyBegi solved it, so I'll piggyback on it.
** Thoughts ** Due to the constraints of the problem, it must be stored at the maximum of about $ O (N) $, so it is not enough to calculate for each leader. Therefore, we use the cumulative sum. Now you can calculate for each reader without having to $ sum $ each time. By the way, the computational complexity of $ sum $ in Python is $ O (N) $. If you understand this far, just do it.
n = int(input())
s = input()
count_e = [0] * n
count_w = [0] * n
for i in range(n):
if i == 0:
if s[i] == 'E':
count_e[i] = 1
else:
count_w[i] = 1
continue
if s[i] == 'E':
count_e[i] = count_e[i-1] + 1
count_w[i] = count_w[i-1]
else:
count_e[i] = count_e[i-1]
count_w[i] = count_w[i-1] + 1
ans = 10 ** 9 #e+w is at most 3*10**It's about 5, but I have a margin
for i in range(n):
if s[i] == 'E':
e = count_e[-1] - count_e[i] #Use cumulative sum
w = count_w[i]
else:
e = count_e[-1] - count_e[i] #Use cumulative sum
w = count_w[i] - 1 #Subtract your share
ans = min(ans,e+w)
print(ans)
I'm glad that I've come up with algorithms that can be used by looking at the constraints. See you again, good night.
Recommended Posts