Pluses and Minuses (Codeforces 1373C)
Tags: Math, math

You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

Input: The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases.The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -.It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.

Output: For each test case print one integer — the value of the $$$res$$$ after the process ends.


Sample Inputs:
3
--+-
---
++--+-

Sample Outputs:
7
9
6

Solution (Python):
from collections import defaultdict

def main():
    s = input()
    c = 0
    sum = 0
    k = 0
    for i in range(len(s)):
        if s[i] == '-':
            c -= 1
        else:
            c += 1
        if c < k:
            sum += i + 1
            k = c
    print(sum + len(s))
for i in range(int(input())):
    main()

Solution (Python):
import sys
input = sys.stdin.readline

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

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    s = readStr()
    n = len(s)
    ans = curr = 0
    for i in range(n):
        curr += 1 if s[i] == '+' else -1
        if curr < 0:
            ans += i + 1
            curr += 1
    ans += n
    return ans
for _ in range(int(input())):
    print(solve())

Solution (Python):
test_cases = int(input())

def handle() -> int:
    s = input()
    current = 0
    total = len(s)
    for i in range(len(s)):
        if s[i] == '-':
            current -= 1
        elif current < 0:
            current = 1
        else:
            current += 1
        if current < 0:
            total += i + 1
    return total
for _ in range(test_cases):
    print(handle())