Balanced Stone Heaps (Codeforces 1623C)
Tags: Greedy, binary search

There are $$$n$$$ heaps of stone. The $$$i$$$-th heap has $$$h_i$$$ stones. You want to change the number of stones in the heap by performing the following process once:   You go through the heaps from the $$$3$$$-rd heap to the $$$n$$$-th heap, in this order.  Let $$$i$$$ be the number of the current heap.  You can choose a number $$$d$$$ ($$$0 \le 3 \cdot d \le h_i$$$), move $$$d$$$ stones from the $$$i$$$-th heap to the $$$(i - 1)$$$-th heap, and $$$2 \cdot d$$$ stones from the $$$i$$$-th heap to the $$$(i - 2)$$$-th heap.  So after that $$$h_i$$$ is decreased by $$$3 \cdot d$$$, $$$h_{i - 1}$$$ is increased by $$$d$$$, and $$$h_{i - 2}$$$ is increased by $$$2 \cdot d$$$.  You can choose different or same $$$d$$$ for different operations. Some heaps may become empty, but they still count as heaps. What is the maximum number of stones in the smallest heap after the process?

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^5$$$). Description of the test cases follows.The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$).The second lines of each test case contains $$$n$$$ integers $$$h_1, h_2, h_3, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$).It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, print the maximum number of stones that the smallest heap can contain.

Note: In the first test case, the initial heap sizes are $$$[1, 2, 10, 100]$$$. We can move the stones as follows.   move $$$3$$$ stones and $$$6$$$ from the $$$3$$$-rd heap to the $$$2$$$-nd and $$$1$$$ heap respectively. The heap sizes will be $$$[7, 5, 1, 100]$$$;  move $$$6$$$ stones and $$$12$$$ stones from the last heap to the $$$3$$$-rd and $$$2$$$-nd heap respectively. The heap sizes will be $$$[7, 17, 7, 82]$$$. In the second test case, the last heap is $$$1$$$, and we can not increase its size.In the third test case, it is better not to move any stones.In the last test case, the final achievable configuration of the heaps can be $$$[3, 5, 3, 4, 3, 3]$$$.

Sample Inputs:
4
4
1 2 10 100
4
100 100 100 1
5
5 1 1 1 8
6
1 2 3 4 5 6

Sample Outputs:
7
1
1
3

Solution (Python):
def main():

    def checkPossible(stones):
        a = h.copy()
        for i in range(n - 1, 1, -1):
            if a[i] < stones:
                return False
            d = min((a[i] - stones) // 3, h[i] // 3)
            a[i] -= 3 * d
            a[i - 1] += d
            a[i - 2] += 2 * d
        return a[0] >= stones and a[1] >= stones
    t = int(input())
    allans = []
    for _ in range(t):
        n = int(input())
        h = readIntArr()
        avg = (sum(h) + n - 1) // n
        twoPowers = []
        b = 1
        while b <= avg:
            twoPowers.append(b)
            b *= 2
        twoPowers.reverse()
        ans = 0
        for b in twoPowers:
            if ans + b <= avg and checkPossible(ans + b):
                ans += b
        allans.append(ans)
    multiLineArrayPrint(allans)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ansArr):
    print('! {}'.format(' '.join([str(x) for x in ansArr])))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()

Solution (Python):
from calendar import c
from math import ceil, inf, log2
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque
mod = 10 ** 9 + 7
mod1 = 998244353
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')

def ok(x):
    cont = [0] * n
    if a[-1] < x:
        return False
    rem = (a[-1] - x - (a[-1] - x) % 3) // 3
    cont[-2] += rem
    cont[-3] += 2 * rem
    for i in range(n - 2, 1, -1):
        if a[i] + cont[i] < x:
            return False
        k = min(a[i] + cont[i] - x, a[i])
        k = (k - k % 3) // 3
        cont[i - 1] += k
        cont[i - 2] += 2 * k
    if a[0] + cont[0] < x or a[1] + cont[1] < x:
        return False
    return True
for _ in range(int(input())):
    n = int(input())
    a = list(map(int, input().split()))
    (l, r) = (min(a), max(a))
    ans = l
    while l <= r:
        m = (l + r) // 2
        if ok(m):
            ans = m
            l = m + 1
        else:
            r = m - 1
    print(ans)

Solution (Python):
import sys
input = sys.stdin.buffer.readline
n = None
h = None

def check(mx_h):
    a = h[:]
    for i in range(n - 1, 1, -1):
        if a[i] > mx_h:
            d = min(a[i] - mx_h, h[i]) // 3
            a[i] -= 3 * d
            a[i - 1] += d
            a[i - 2] += 2 * d
    return min(a) >= mx_h
for _ in range(int(input())):
    n = int(input())
    h = list(map(int, input().split()))
    l = 0
    r = 10 ** 9
    while l != r:
        m = (l + r + 1) // 2
        if check(m):
            l = m
        else:
            r = m - 1
    print(l)