Maximum Product Strikes Back (Codeforces 1660D)
Tags: Math, two pointers

You are given an array $$$a$$$ consisting of $$$n$$$ integers. For each $$$i$$$ ($$$1 \le i \le n$$$) the following inequality is true: $$$-2 \le a_i \le 2$$$.You can remove any number (possibly $$$0$$$) of elements from the beginning of the array and any number (possibly $$$0$$$) of elements from the end of the array. You are allowed to delete the whole array.You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them. The product of elements of an empty array (array of length $$$0$$$) should be assumed to be $$$1$$$.

Input: The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test.Then the descriptions of the input test cases follow.The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) —the length of array $$$a$$$.The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_i| \le 2$$$) — elements of array $$$a$$$.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, output two non-negative numbers $$$x$$$ and $$$y$$$ ($$$0 \le x + y \le n$$$) — such that the product (multiplication) of the array numbers, after removing $$$x$$$ elements from the beginning and $$$y$$$ elements from the end, is maximal.If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be $$$1$$$.

Note: In the first case, the maximal value of the product is $$$2$$$. Thus, we can either delete the first three elements (obtain array $$$[2]$$$), or the last two and one first element (also obtain array $$$[2]$$$), or the last two elements (obtain array $$$[1, 2]$$$). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".In the second case, the maximum value of the product is $$$1$$$. Then we can remove all elements from the array because the value of the product on the empty array will be $$$1$$$. So the answer is "3 0", but there are other possible answers.In the third case, we can remove the first two elements of the array. Then we get the array: $$$[-2, 2, -1]$$$. The product of the elements of the resulting array is $$$(-2) \cdot 2 \cdot (-1) = 4$$$. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 0".

Sample Inputs:
5
4
1 2 -1 2
3
1 1 -2
5
2 0 -2 2 -1
3
-2 -1 -1
3
-1 -2 -2

Sample Outputs:
0 2
3 0
2 0
0 1
1 0

Solution (Python):
from math import sqrt, ceil
import os
import sys
from collections import defaultdict, deque
from io import BytesIO, IOBase
from collections import Counter
from functools import lru_cache
from collections import deque

def main():
    for _ in range(int(input())):
        n = int(input())
        arr = list(map(int, input().split()))
        (l_ind, r_ind) = (0, n)
        res = 0
        pl = 0
        pr = 0
        nl = None
        nv = None
        temp = 1
        c = 0
        for (i, el) in enumerate(arr):
            if el > 0:
                temp *= 1
            elif el < 0:
                temp *= -1
            else:
                temp = 0
            if abs(el) == 2:
                c += 1
            if temp > 0:
                if c > res:
                    res = c
                    l_ind = pl
                    r_ind = i
            elif temp < 0:
                if nv == None:
                    nl = i
                    nv = c
                elif c - nv > res:
                    res = c - nv
                    l_ind = nl + 1
                    r_ind = i
            else:
                pl = i + 1
                pr = 0
                nl = None
                nv = None
                temp = 1
                c = 0
        (a, b, v) = (l_ind, r_ind, res)
        if v == 0:
            print(n, 0)
        else:
            print(a, n - b - 1)
input = lambda : sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()

Solution (Python):
from math import sqrt, ceil
import os
import sys
from collections import defaultdict, deque
from io import BytesIO, IOBase
from collections import Counter
from functools import lru_cache
from collections import deque

def main():
    for _ in range(int(input())):
        n = int(input())
        arr = list(map(int, input().split()))
        (l_ind, r_ind) = (0, n)
        res = 0
        pl = 0
        pr = 0
        nl = None
        nv = None
        temp = 1
        c = 0
        for (i, el) in enumerate(arr):
            if el > 0:
                temp *= 1
            elif el < 0:
                temp *= -1
            else:
                temp = 0
            if abs(el) == 2:
                c += 1
            if temp > 0:
                if c > res:
                    res = c
                    l_ind = pl
                    r_ind = i
            elif temp < 0:
                if nv == None:
                    nl = i
                    nv = c
                elif c - nv > res:
                    res = c - nv
                    l_ind = nl + 1
                    r_ind = i
            else:
                pl = i + 1
                pr = 0
                nl = None
                nv = None
                temp = 1
                c = 0
        (a, b, v) = (l_ind, r_ind, res)
        if v == 0:
            print(n, 0)
        else:
            print(a, n - b - 1)
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()

Solution (Python):
def solution(arr, n):
    (startZeroIdx, endZeroIdx, cntZero) = (-1, -1, 0)
    (firstNegIdx, lastNegIdx) = (-1, -1)
    (cntNeg, cnt2) = (0, 0)
    ans = []
    for i in range(len(arr)):
        if abs(arr[i]) == 2:
            cnt2 += 1
        if arr[i] < 0:
            cntNeg += 1
            if firstNegIdx == -1:
                firstNegIdx = i
            lastNegIdx = i
        if arr[i] == 0:
            cntZero += 1
            if cntZero == 1:
                startZeroIdx = i
            endZeroIdx = i
            if cntZero == 2:
                if cntNeg % 2 == 0:
                    ans.append((cnt2, startZeroIdx + 1, endZeroIdx - 1))
                else:
                    (cnt2FromFirst0, cnt2FromLast0) = (0, 0)
                    for j in range(startZeroIdx + 1, firstNegIdx + 1):
                        if abs(arr[j]) == 2:
                            cnt2FromFirst0 += 1
                    for j in range(lastNegIdx, endZeroIdx):
                        if abs(arr[j]) == 2:
                            cnt2FromLast0 += 1
                    if cnt2FromFirst0 < cnt2FromLast0:
                        ans.append((cnt2 - cnt2FromFirst0, firstNegIdx + 1, endZeroIdx - 1))
                    else:
                        ans.append((cnt2 - cnt2FromLast0, startZeroIdx + 1, lastNegIdx - 1))
                startZeroIdx = endZeroIdx
                cntZero = 1
                cnt2 = 0
                cntNeg = 0
                (firstNegIdx, lastNegIdx) = (-1, -1)
    ans.sort()
    (c2, l, r) = ans[len(ans) - 1]
    print(str(l - 1) + ' ' + str(n - r))
if __name__ == '__main__':
    t = int(input())
    for i in range(t):
        n = int(input())
        arr = list(map(int, input().split()))
        arr.append(0)
        arr.insert(0, 0)
        solution(arr, n)