Problem:


Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

2 \leq N \leq 3 \times 10^5

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3



Sample input:
5
WEEWW


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
n = input()
s = raw_input()

result = 300000

for i in range(n):
    cnt = 0
    a = s[:i].replace("E", "")
    b = s[i+1:].replace("W", "")
    result = min(len(a) + len(b), result)

print result

Submission status: Time Limit Exceeded

Solution code:

n = input()
s = raw_input()

result = 300000

for i in range(n):
    cnt = 0
    for j in range(n):
        if i < j:
            if s[j] == "E":
                cnt = cnt + 1
        elif j < i:
            if s[j] == "W":
                cnt = cnt + 1
    result = min(result, cnt)
print result

Submission status: Time Limit Exceeded

Solution code:
def getSocre(i, s):
    w = s[0:i-1].count('W') if (i-1) >= 0 else 0
    e = s[i+1:len(s)].count('E') if (i+1) < len(s) else 0
    return w + e


n = int(input())
s = input()

score = n
for i in range(n):
    score2 = getSocre(i, s)
    if score2 < score:
        score = score2

print(score)

Submission status: Time Limit Exceeded

Solution code:
# https://beta.atcoder.jp/contests/arc098/tasks/arc098_a
length = int(input())
str = input()

# 人数を計算する
def count(s, lp, min):
	cnt = 0
	for i in range(len(s)):
		if i < lp and s[i] == 'W':
			cnt += 1
		elif i > lp and s[i] == 'E':
			cnt += 1
		if cnt >= min:
			return cnt # 最小超えたら評価をやめる
	return cnt

min = length
for lp in range(length):
	cnt = count(str, lp, min)
	if min > cnt:
		min = cnt

print(min)

Submission status: Time Limit Exceeded

Solution code:
# https://beta.atcoder.jp/contests/arc098/tasks/arc098_a
_ = input()
str = input()

# 人数を計算する
def count(s, lp):
	cnt = 0
	for i in range(len(s)):
		if i < lp and s[i] == 'W':
			cnt += 1
		elif i > lp and s[i] == 'E':
			cnt += 1

	return cnt

min = len(str)
for lp in range(len(str)):
	cnt = count(str, lp)
	if min > cnt:
		min = cnt

print(min)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

N=int(input())
S=input()

West=[]
East=[]

for i in range(N): 
	w=0
	e=0
	for j in range(i+1,N):
		if S[j]=="E":
			e+=1
	for j in range(0,i):
		if S[j]=="W":
			w+=1
	West.append(w)
	East.append(e)
min=West[0]+East[0]
min_i=0
for i in range(1,N):
	if min>West[i]+East[i]:
		min=West[i]+East[i]
		min_i=i
print(min)

Submission status: Time Limit Exceeded

Solution code:
#coding: utf-8
import sys

# 入力
n = int(sys.stdin.readline().strip())
s = list(sys.stdin.readline().strip())


counts = []

for i in range(n):
    counts.append(0)
    for j in range(len(s)):
        if (i != j):
            if (i > j and s[j] == 'W'):
                counts[i] = counts[i] + 1
            elif(i < j and s[j] == 'E'):
                counts[i] = counts[i] + 1



# 出力
print(min(counts))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()

tmp = [int(p.replace('W', '-1')) if p == 'W' else int(p.replace('E', '1')) for p in list(S)]

result = []
cnt = 0
for CTO in range(N):
    for MEM in range(N):
        if MEM == CTO:
            continue
        if CTO < MEM:
            if tmp[CTO] == -1:
                if (tmp[MEM] + tmp[CTO]) == 0:
                    cnt += 1
            if tmp[CTO] == 1:
                if (tmp[MEM] + tmp[CTO]) != 0:
                    cnt += 1

        if MEM < CTO:
            if tmp[CTO] == -1:
                if (tmp[MEM] + tmp[CTO]) != 0:
                    cnt += 1
            if tmp[CTO] == 1:
                if  (tmp[MEM] + tmp[CTO]) == 0:
                    cnt += 1
    result.append(cnt)
    cnt = 0

result_x = [ result[i] for i in range(N) if result[i] != 0]
print(min(result_x))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()

min_count = n
count=0

for i in range(n):
    for j in range(i):
        if s[j] != 'E':
            count = count + 1
    for j in range(i+1, n):
        if s[j] != 'W':
            count = count + 1
    if count < min_count:
        min_count = count
    count = 0
print(min_count)

Submission status: Time Limit Exceeded

Solution code:
a = int(input())
b = str(input())
res = []
for i in range(a):

    l = b[0:i]
    r = b[i:a]
  
    lk_center = l.count("W") + r.count("E")
    res.append(lk_center)

else:
    rrr = min(res)
    print(rrr)

Submission status: Time Limit Exceeded

Solution code:
import collections
from collections import Counter
N=int(input())
A=input()
#A=list(A)
min_output=len(A)
for j in range (len(A)):
    min_=collections.Counter(A[0:j])["W"]+collections.Counter(A[j+1:])["E"]
    if min_output>min_:
        min_output=min_
print(min_output)

Submission status: Time Limit Exceeded

Solution code:
n =int(input())
S=input()

idx = 0
num=n
for s in range(n):
    nn = 0
    
    for ss in range(s):
        if S[ss] == 'W':
            nn += 1
    for ss in range(s + 1, n):
        if S[ss] == 'E':
            nn += 1

    if nn < num:
        num=nn
        idx = s
    if num == 1:
        break
print(num)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
n = int(sys.stdin.readline())
s = sys.stdin.readline()

def count(s, idx):
	w = s.count("W", 0, idx)
	e = s.count("E", idx + 1)

	return w + e

m = count(s, 0)
j = 0

for i in range(1, len(s)): 
	m2 = count(s, i)
	if m2 < m:
		m = m2
		j = i

print(m)

Submission status: Time Limit Exceeded

Solution code:
import collections
from collections import Counter
N=int(input())
A=input()
#A=list(A)
min_output=len(A)
for j in range (len(A)):
    if min_output>collections.Counter(A[0:j])["W"]+collections.Counter(A[j+1:])["E"]:
        min_output=collections.Counter(A[0:j])["W"]+collections.Counter(A[j+1:])["E"]
print(min_output)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
n = int(sys.stdin.readline())
s = sys.stdin.readline()[0:n]

def count(s, idx):
	w = s[0:idx].count("W")
	e = s[idx+1:len(s)].count("E")

	return w + e

m = count(s, 0)
j = 0
for i in range(1, len(s)): 
	m2 = count(s, i)
	if m2 < m:
		m = m2
		j = i
print(m)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()

cost = 10000000
for i in range(0, n):
    cost = min(cost, s[:i].count('W') + s[(i+1):].count('E'))
print(cost)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()

cost = list()
for i in range(0, n):
    cost.append(s[:i].count('W') + s[(i+1):].count('E'))

print(min(cost))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
count = np.array([0]*N)
S = input()

i = 0
for s in S:
  
  if s=="E":
    count[0:i] += 1
    
  else:
    count[i+1:N+1] += 1
  
  i += 1

print(min(count))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=input()
#A=list(A)
min_output=len(A)
for j in range (len(A)):
    if min_output>A[0:j].count("W")+A[j+1:].count("E"):
        min_output=A[0:j].count("W")+A[j+1:].count("E")
print(min_output)

Submission status: Time Limit Exceeded

Solution code:
from sys import stderr
from functools import reduce
from operator import add
def f(): [int(i) for i in input().split()]
def debug(*x): stderr.write(reduce(add,repr(x)).strip("()',")+'\n')

n = int(input())
s = list(input())

longest = {"E":(0,1),"W":(0,1)}
# index,num of people who is E

i = 0
state = ""
po = 0
while i < n:
    debug(i)
    if po == 0:
        debug("po==0")
        po += 1
        state = s[i]
        i += 1
    else:
        if s[i] == state:
            debug(state,"po increased")
            po += 1
            i += 1
        else:
            debug("po changed")
            if longest[state][1] <= po:
                if state == "E":
                    longest[state] = (i-1, po)
                else:
                    longest[state] = (i-po-1,po)
            po = 0
            i += 1

debug(longest)
if longest["E"][1] < longest["W"][1]:
    leader = longest["W"][0]
else:
    leader = longest["E"][0]

ans = 0
debug(leader,s)
for i in range(leader):
    if s[i] == "W":
        debug(i)
        ans += 1
for i in range(leader+1,n):
    if s[i] == "E":
        debug(i)
        ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def count(item, str1):
    counter = 0
    for c in str1:
        if c == item:
            counter += 1
    return counter

N = int(input())
S = input()
_min = -1
for i in range(N):
    left_str = S[:i]
    right_str = S[i+1:]
    left = count('W', left_str)
    right = count('E', right_str)
    total = left + right
    if _min == -1:
        _min = total
    elif total < _min:
        _min = total
print(_min)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(input())
for i in range(n):
    if a[i] == 'E':
        a[i] = 1
    else:
        a[i] = 0

ans = 99999999999999999999
# print(a)
for i in range(n-1):
    l = 0
    r = 0
    if i > 0:
        l = sum(a[0:i])
        # print("l",a[0:i])
        l = abs(i-l)
    if i < n-1:
        # print("r",a[i+1:])
        r = sum(a[i+1:])
    # print(i,l,r)
    ans = min(l+r,ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
a=[]
for i in s:
    if i=='W': a.append(1)
    else: a.append(-1)
a2=[-1*i for i in a]
suma=[sum(a[i+1:]) for i in range(len(a))]
suma2=[sum(a2[:i]) for i in range(len(a))]
#print(a,a2)
count=0
for i in range(len(a)):
    d=suma[i]+suma2[i]
    if count<d:count=d
    #print(sum(a[i+1:]),sum(a2[:i]),d)
print((n-1-count)//2)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=input()
A=list(A)
min_output=len(A)
for j in range (len(A)):
    if min_output>A[0:j].count("W")+A[j+1:].count("E"):
        min_output=A[0:j].count("W")+A[j+1:].count("E")
print(min_output)

Submission status: Time Limit Exceeded

Solution code:
def a(n, s):
    score = n
    for i in range(n):
        tmp = 0
        for j, c in enumerate(s):
            if j is i:
                continue
            if j < i:
                if c is 'W':
                    tmp += 1
            else:
                if c is 'E':
                    tmp += 1
        if tmp < score:
            score = tmp
    print(score)


n = int(input())
s = input()

a(n, s)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=input()
A=list(A)
for i in range (len(A)):
    if A[i]=='W':
        A[i]=-1#westside
    else:
        A[i]=1#eastside
min_output=len(A)
for j in range (len(A)):
    if min_output>A[0:j].count(-1)+A[j+1:].count(1):
        min_output=A[0:j].count(-1)+A[j+1:].count(1)
print(min_output)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
a=[]
for i in s:
    if i=='W': a.append(1)
    else: a.append(-1)
a2=[-1*i for i in a]
#print(a,a2)
count=0
for i in range(len(a)):
    d=sum(a[i+1:])+sum(a2[:i])
    if count<d:count=d
    #print(sum(a[i+1:]),sum(a2[:i]),d)
print((n-1-count)//2)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())
num_list = [S[:i].count("E")+S[i+1:].count("W") for i in range(N-1)[1:]]
ans = N - 1 - max([max(num_list), S[1:].count("W"), S[:N-1].count("E")])
print(str(ans))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int( input() )
count = np.array([0]*N)
S = input()

for i in range(N):
    s = S[i]
    
    count[0:i] += int(s=="E")
    count[i+1:N+1] += int(s=="W")

print(min(count))

Submission status: Time Limit Exceeded

Solution code:
da  = int(input())

k = list(input())
p = [0]*da
for i in range(da):
  for j in range(da):
    if k[i] == "W" and j < i:
      p[j] += 1
    elif k[i] == "E" and j > i:
      p[j] += 1
      
print(da - max(p)-1)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())

accLeft = [0]
accRight = [0]

tmp = 0
for c in S:
  tmp += int(c == 'W')
  accLeft.append(tmp)
accLeft.append(0)

tmp = 0
for c in S[::-1]:
  tmp += int(c == 'E')
  accRight = [tmp] + accRight
accRight = [0] + accRight

print(min([accLeft[i-1] + accRight[i+1] for i in range(1, N+1)]))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    ans = sys.maxsize
    for i in range(N):
        ans = min(ans, S[:i].count('W') + S[i + 1:].count('E'))
    return ans


def main():
    N = read_int()
    S = read_str()
    print(slv(N, S))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
n = int(input())
s = input()
ans = float('inf')
for i in range(n):
    if i==0:
        cnt = s[1:].count('E')
    elif i==n-1:
        cnt = s[:n-2].count('W')
    else:
        cnt = s[i+1:].count('E') + s[:i-1].count('W')
    ans = min(ans, cnt)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())
num = []
for i in range(N):
    if i == 0:
        num.append(S[1:].count("W"))
    elif i == N-1:
        num.append(S[:N-1].count("E"))
    else:
        num.append(S[:i].count("E")+S[i+1:].count("W"))
ans = N - 1 - max(num)
print(str(ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()

a = N
for i in range(N):
    a = min(a, S[:i].count('W')+S[i+1:].count('E'))

print(a)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = str(input())
cou = n
lis = []
for i in range(n):
    if i == 0:
        lis.append(s[i+1:n].count("E"))
    else:
        lis.append(s[0:i].count("W")+s[i+1:n].count("E"))
print(min(lis))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	C_fix
# CreatedDate:  2020-09-27 01:13:48 +0900
# LastModified: 2020-09-27 01:29:07 +0900
#


import os
import sys
# import numpy as np
# import pandas as pd


def main():
    N = int(input())
    S = input()
    RW_cnt = S.count("W")
    RE_cnt = S.count("E")
    LW_cnt = 0
    LE_cnt = 0
    if S[0] == "W":
        RW_cnt -= 1
        LW_cnt = 1
    else:
        RE_cnt -= 1
        LE_cnt = 1
    ans = RE_cnt
#    print("RW_cnt, RE_cnt, LW_cnt, LE_cnt")
    for i in range(1, N):
        if i == N-1:
            cnt = LW_cnt
        else:
            cnt = LW_cnt + RE_cnt
        if cnt < ans:
            ans = cnt
        if S[i] == "E":
            LE_cnt += 1
            RE_cnt -= 1
        else:
            LW_cnt += 1
            RW_cnt -= 1
#        print(RW_cnt, RE_cnt, LW_cnt, LE_cnt)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
S = input()
cnt = 0
for i in range(1, N):
	if S[i] == 'W':
		cnt += 1
max = cnt
for i in range(1, N):
	if S[i-1] == 'E':
		cnt += 1
	if S[i] == 'W':
		cnt -= 1
	if max < cnt:
		max = cnt
print(N - max - 1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

#import
#import math
#import numpy as np
N = int(input())
S = list(input())

re = S.count("E")
rw = N - re
le = 0
lw = 0

ans = 10**9

for i in range(N):
    if S[i] == "E":
        re -= 1
        ans = min(ans, re + lw)
        le += 1
    else:
        rw -= 1        
        ans = min(ans, re + lw)
        lw += 1

print(ans)

Submission status: Accepted

Solution code:
# author:  Taichicchi
# created: 22.09.2020 12:19:17

import sys

from collections import Counter

N = int(input())

S = input()

e = [0]
w = [0]

for s in S:
    if s == "W":
        w += [w[-1] + 1]
        e += [e[-1]]
    elif s == "E":
        w += [w[-1]]
        e += [e[-1] + 1]

ans = 3 * (10 ** 5) + 1

for i in range(N):
    c = w[i]
    c += e[N] - e[i + 1]
    ans = min(c, ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
def input():
  return sys.stdin.readline().rstrip()

N=int(input())
S=input()

w_sum,e_sum=[0],[0]

for x in S:
  if x=="W":
    w_sum.append(w_sum[-1]+1)
  else:
    w_sum.append(w_sum[-1])
w_sum.append(0)

RS=S[::-1]
for x in RS:
  if x=="E":
    e_sum.append(e_sum[-1]+1)
  else:
    e_sum.append(e_sum[-1])
e_sum.append(0)
e_sum.reverse()

ans=float("inf")
for i in range(1,N+1):
  ans=min(ans,w_sum[i-1]+e_sum[i+1])

print(ans)

Submission status: Accepted

Solution code:
import collections

def main():
    N = int(input())
    S = list(input())
    Scount = collections.Counter(S)
    Wcount = Scount['W']
    Ecount = Scount['E']

    if S[0] == "W":
        Wcount -= 1
    else:
        Ecount -= 1
    ans = Ecount
    L = [0, 0]; R = [Wcount, Ecount]
    for i in range(N-1):
        sl = S[i]
        s = S[i+1]
        if sl == 'W':
            L[0] += 1
        else:
            L[1] += 1
        if s == 'W':
            R[0] -= 1
        else:
            R[1] -= 1
        cnt = L[0] + R[1]
        ans = min(ans, cnt)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
S = input()

ans_temp = 0
for i in range(1, N):
    if S[i] == 'E':
        ans_temp += 1
ans = ans_temp

for i in range(1, N):
    if S[i] == 'E':
        ans_temp -= 1
    if S[i-1] == 'W':
        ans_temp += 1
    ans = min(ans, ans_temp)

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
S = input()
conS = Counter(S)
NuE = conS['E']
NuW = conS['W']
def Change(x,lefW,rigE):
    if x == 'W':
        return lefW + rigE -1
    else:
        return lefW + rigE
lefW = 0
rigE = NuE
Ans = N
for i in S:
    if i == 'E':
        rigE -= 1
    else:
        lefW += 1
    Ans = min(Ans, Change(i,lefW,rigE))
print(Ans)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    N = int(input())
    E = [0]*(N+1)
    W = [0]*(N+1)
    for i, s in enumerate(input()):
        if s == "E":
            E[i+1] = 1
        elif s == "W":
            W[i+1] = 1
        E[i+1] += E[i]
        W[i+1] += W[i]
    ans = 3*10**5
    for i in range(N):
        if i == 0:
            ans = min(ans, E[N]-E[1])
            continue
        if i == N-1:
            ans = min(ans, W[i])
            continue
        ans = min(ans, E[N]-E[i+1] + W[i])
    print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    S = input()
    ans = tmp = S.count('E')
    prev = ''
    for c in S:
        if c == 'E':
            tmp -= 1
        if prev == 'W':
            tmp += 1
        ans = min(ans,tmp)
        prev = c
    print(ans)
main()

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline
N = int(input())
peoples = list(input().strip())

E = 0
W = 0
for p in peoples:
    if p == "E":
        E += 1
    else:
        W += 1

ans = float("inf")
tmp = E
for i in range(N):
    if peoples[i] == "E":
        tmp -= 1
    if 0 < i and peoples[i-1] == "W":
        tmp += 1
    ans = min(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
e = S.count('E')
X = [0]*(N+1)
X[0] = e
Y = [0]*(N+1)
Y[N] = N-e
for i in range(1, N+1):
    X[i] = X[i-1]-(S[i-1] == 'E')
for i in range(N, 0, -1):
    Y[i-1] = Y[i]-(S[i-1] == 'W')
ans = [X[i+1]+Y[i] for i in range(N)]
# print(X)
# print(Y)
print(min(ans))

Submission status: Accepted

Solution code:
N=int(input())
S=input()

LW=[0]*N
for i in range(1,N):
  if S[i-1]=="W":
    LW[i]=LW[i-1]+1
  else:
    LW[i]=LW[i-1]

RE=[0]*N
for i in range(N-2,-1,-1):
  if S[i+1]=="E":
    RE[i]=RE[i+1]+1
  else:
    RE[i]=RE[i+1]

ans=10**9
for i in range(N):
  ans=min(ans,LW[i]+RE[i])
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
rwc = S.count('W')
rec = N-rwc
lwc = 0
lec = 0
if S[0] == 'W':
    rwc -= 1
else:
    rec -= 1
mi = rec
for i in range(1,N):
    if S[i] == 'W':
        rwc -= 1
    else:
        rec -= 1
    if S[i-1] == 'W':
        lwc += 1
    else:
        lec += 1

    muku = lwc + rec
    mi = min(mi,muku)
print(mi)

Submission status: Accepted

Solution code:
N = int(input())
S = list(map(str,input()))
En = S[1:].count("E")
Sn = S[1:].count("W")
res = [En]
cnt = En
for i, s in enumerate(S):
    if i == 0:
        continue
    if s == "E":
        cnt -= 1
    if S[i-1] == "W":
        cnt += 1
    res.append(cnt)
print(min(res))

Submission status: Accepted

Solution code:
import re
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
import functools
def v(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 6)
mod = 10**9+7
cnt = 0
ans = 0
inf = float("inf")
al = "abcdefghijklmnopqrstuvwxyz"
AL = al.upper()

n = k()
s = v()
e = list(itertools.accumulate([1 if i=="E" else 0 for i in s]))
w = list(itertools.accumulate([1 if i=="W" else 0 for i in s]))

for i in range(n):
    cnt = e[-1]-e[i]+w[i]
    if mod > cnt:
        mod,ans = cnt,i
if ans == 0:
    mod -= 1

print(mod)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

cnt = 0
min_cnt = 3 * 10**5
for i in range(1, N):
    if S[i] == 'E':
        cnt += 1
min_cnt = cnt
# print(cnt)

for i in range(1, N):
    if S[i-1:i+1] == "EE":
        cnt -= 1
    elif S[i-1:i+1] == "EW":
        cnt += 0
    elif S[i-1:i+1] == "WE":
        cnt += 0
    elif S[i-1:i+1] == "WW":
        cnt += 1
    min_cnt = min(min_cnt, cnt)
print(min_cnt)

Submission status: Accepted

Solution code:
n= int(input())
s = list(input())
a = s[1:].count('E')
g = [a]
b = 0
c = a
for i in range(1,n):
  if s[i-1]=='W':
    b+=1
  if s[i]=='E':
    c-=1
  g.append(b+c)
print(min(g))

Submission status: Accepted

Solution code:
n=int(input())
s=input()
data=[0]*(n+1)
for i in range(n):
  if s[i]=='E':
    data[i+1]=data[i]+1
  else:
    data[i+1]=data[i]
print(min(i-data[i]+data[n]-data[i+1] for i in range(n)))

Submission status: Accepted

Solution code:
n=int(input())
s=input()
s=s[::-1]
e=0;w=0
for i in range(n):
    e+=(s[i]=="E")
    w+=(s[i]=="W")

w2=w
e2=0
ans=n-1
for i in range(n):
    w2-=(s[i]=="W")
    ans=min(ans,w2+e2)
    e2+=(s[i]=="E")
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
ans=s[1:].count('E') #soppo-count
tmp=ans
for i in range(1,n):
  if s[i-1]=='W': tmp+=1
  if s[i]=='E': tmp-=1
  ans=min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
E = [0]*(N+1)
W = [0]*(N+1)
for i in range(N):
  W[i+1]+=W[i]
  if S[i] == "W":
    W[i+1]+=1
for i in reversed(range(N)):
  E[i]+=E[i+1]
  if S[i] == "E":
    E[i]+=1
W = W[1:]
E = E[:-1]

ans = float('inf')
for i in range(N):
  ans = min(W[i]+E[i]-1, ans)
print(ans)

Submission status: Accepted

Solution code:
#77 C - Attention
N = int(input())
S = input()

# lw[i]: i より左にいる人の中で W を向いている人数をカウント
lw = [0]*N
cntw = 0
# 左に人がいるのは [1,N-1] 
for i in range(1,N):
    if S[i-1] == 'W':
        cntw += 1
    lw[i] = cntw

# re[j]: j より右にいる人の中で E を向いている人数をカウント
re = [0]*N
cnte = 0
# 右に人がいるのは [0,N-2]
for j in range(N-2,-1,-1):
    if S[j+1] == 'E':
        cnte += 1
    re[j] = cnte

ans = 10**10
for i,j in zip(lw,re):
    tot = i+j
    ans = min(tot,ans)
print(ans)

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right #func(リスト,値)
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import *

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x):
        self.setdefault(x,0)
        self[x] += 1

N = intput()
S = input()
re = 0
for i in range(N):
    re = re+1 if S[i]=='E' else re
lw = 0
ans = INF
for i in range(N):
    re = re-1 if S[i]=='E' else re
    ans = min(ans,re+lw)
    lw = lw+1 if S[i]=='W' else lw
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
e = s.count('E')
w = 0
ans = 3 * (10 ** 5)
for i in s:
    if i == 'E':
        e -= 1
    ans = min(ans,e + w)
    if i == 'W':
        w += 1
print(ans)

Submission status: Accepted

Solution code:
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
    n = I()
    s = S()
    right, left = 0, 0
    ans = n
    for i in s:
        right += 1 if i=="E" else 0

    for i, char in enumerate(s):
        right -= 1 if char=="E" else 0
        cnt = left + right
        ans = min(ans,cnt)
        left += 1 if char=="W" else 0

    print(ans)
main()

Submission status: Accepted

Solution code:
import collections
n=int(input())
s=list(input())
cnte=s.count('E')
cntw=s.count('W')
#print(cnte,cntw)
ans=n
a=0
b=0
for i in range(n):
    if s[i]=='E':
        a+=1
    elif s[i]=='W':
        b+=1
    c=cnte-a
    d=cntw-b
    tmp=b+c
    if s[i]=='W':
        tmp-=1
    ans=min(ans,tmp)
#    print(i,tmp)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
a = [str(c) for c in s]

x = a.count('E')
if a[0] == 'E':
    x -= 1
y = x
for i in range(n-1):
    if a[i] == 'W':
        if a[i+1] == 'W':
            x += 1
        else:
            x = x
    else:
        if a[i+1] == 'W':
            x = x
        else:
            x -= 1
    if y > x:
        y = x
        



print(y)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/arc098/tasks/arc098_a

import sys
from collections import Counter
# sys.setrecursionlimit(100000)


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    n = input_int()
    S = input()
    count = Counter(S)
    left_w = 0
    left_e = 0
    ans = len(S) + 1
    for i in range(len(S)):
        if S[i] == "E":
            ans = min(ans, left_w + (count["E"] - left_e - 1))
        else:
            ans = min(ans, left_w + (count["E"] - left_e))
        if S[i] == "W":
            left_w += 1
        else:
            left_e += 1
    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = input()
tb1 = [0]*n
tb2 = [0]*n
for i in range(1,n):
  if s[i-1]=='E':
    tb1[i] = tb1[i-1]+1
  else:
    tb1[i] = tb1[i-1]
for i in range(n-2,-1,-1):
  if s[i+1]=='W':
    tb2[i] = tb2[i+1]+1
  else:
    tb2[i] = tb2[i+1]    
tb = [k+l for k,l in zip(tb1,tb2)]
print(n-max(tb)-1)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
w, e = [0] * (n + 1), [0] * (n + 1)
ans = float("inf")
for i in range(n):
    if s[i] == "W":
        w[i + 1] = w[i] + 1
    else:
        w[i + 1] = w[i]

    if s[n - i - 1] == "E":
        e[i + 1] = e[i] + 1
    else:
        e[i + 1] = e[i]

for j in range(1, n + 1):
    ans = min(ans, w[j] + e[n - j + 1])

print(ans - 1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    S = input()

    wr = S.count('W')
    er = S.count('E')
    # print(wr, er)
    wl = 0
    el = 0
    ans = INF
    for s in S:
        if s == 'W':
            wr -= 1
            ans = min(ans, er+wl)
            wl += 1
        else:
            er -= 1
            ans = min(ans, er+wl)
            el += 1
        # print(wr, er, wl, el)
        # print(s, ans)
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N = int(input())
S = input()

cum_sum_w = [0] * (N + 1)
cum_sum_e = [0] * (N + 1)


for i in range(N):

    if (S[i] == "W"):
        cum_sum_w[i+1] = cum_sum_w[i] + 1
        cum_sum_e[i+1] = cum_sum_e[i] + 0
    else:
        cum_sum_w[i+1] = cum_sum_w[i] + 0
        cum_sum_e[i+1] = cum_sum_e[i] + 1

ans = 10**100  

for i in range(N):
    tmp_ans = cum_sum_w[i] + (cum_sum_e[N] - cum_sum_e[i + 1])
    ans = min(ans,tmp_ans)
    
print(ans)