Temperature Balance
Source: codechef
Difficulty: 1245

Temperature Balance
There are$N$chambers of water in a line. Between the$i$-th chamber and the$(i+1)$-th chamber for each$1 \le i < N$, there is a wall blocking heat from moving between the two chambers. The water in the$i$-th chamber has a temperature level of$A_i$. Additionally, it is known in advance that the sum of$A_i$is$0$.
Each second, you lift exactly one wall, letting heat move between two chambers. Then, the temperature level of the
hotter side
decreases by$1$, while that of the
colder side
increases by$1$. Formally:
Each second, you choose an integer$i$($1 \le i < N$), and lift the wall between the$i$-th chamber and the$(i+1)$-th chamber. Then, the following happens.
If$A_i>A_{i+1}$currently, the two temperature values change to$A_i := A_i-1$and$A_{i+1} := A_{i+1}+1$the exact next second.
If$A_i<A_{i+1}$currently, the two temperature values change to$A_i := A_i+1$and$A_{i+1} := A_{i+1}-1$the exact next second.
If$A_i=A_{i+1}$currently, nothing happens for one second.
After this second, the chamber closes.
Please find the
minimum number of seconds
needed to make all temperature levels exactly$0$. It can be shown that it is always possible to make all temperature levels exactly$0$in a finite number of seconds.
Input Format
The first line of input will contain a single integer$T$, denoting the number of test cases.
Each test case consists of multiple lines of input.
The first line of input contains$N$- the number of chambers
The second line contains$N$integers,$A_1, A_2, ..., A_N$representing the temperature levels of the chambers.
Output Format
For each test case, print the minimum seconds needed.
Constraints$1 \leq T \leq 10^4$$1 \leq N \leq 5 \cdot 10^5$$-10^6 \le A_i \le 10^6$The sum of$A_i$over all$1 \le i \le N$is exactly$0$.
The sum of$N$over all test cases won't exceed$5 \cdot 10^5$.
Sample 1:
Explanation:
Test Case 1
: One can make all temperature levels$0$in$3$seconds by the following process.
Second$0$: Lift the wall between the$1$st chamber and the$2$nd chamber. Then$a$becomes$[0,1,0,-1]$at Second$1$.
Second$1$: Lift the wall between the$2$nd chamber and the$3$rd chamber. Then$a$becomes$[0,0,1,-1]$at Second$2$.
Second$2$: Lift the wall between the$3$rd chamber and the$4$th chamber. Then$a$becomes$[0,0,0,0]$at Second$3$.
It can be shown that one cannot make all temperature levels$0$in$2$seconds. Therefore, the minimum answer is$3$.

Sample Input:
5
4
1 0 0 -1
10
2 0 1 0 0 0 0 -1 0 -2
8
2 0 -1 0 0 1 0 -2
10
2 0 0 0 1 -1 0 0 0 -2
14
6 0 0 3 0 -4 0 1 0 0 0 -10 0 4

Sample Output:
3
23
11
19
78

C++ solution:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define pb push_back
#define endl "\n"
#define F first
#define S second
#define vl vector<ll>
#define vi vector<int>
#define pii pair<int, int>
#define ha cout << "YES\n"
#define na cout << "NO\n"
#define all(x) x.begin(), x.end()
#define mod 1000000007
ll dx[] = {1, -1, 0, 0, 1, 1, -1, -1};
ll dy[] = {0, 0, 1, -1, 1, -1, 1, -1};
char dir[] = {'D', 'U', 'R', 'L'};
const int N = 1e6 + 5;
void solve()
{
    int n;
    cin >> n;
    vl v(n);
    for (auto &x : v)
        cin >> x;
    for (int i = 1; i < n; i++)
        v[i] += v[i - 1];
    ll ans = 0;
    for (int i = 0; i < n; i++)
        ans += abs(v[i]);
    cout << ans << endl;
}
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t;
    while (t--)
        solve();
    return 0;
}

Go solution:
package main



import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)



func main() {
    
    
             reader := bufio.NewReader(os.Stdin)

    
    Ttt, _ := strconv.Atoi(readLine(reader))


            results := make([]int64, Ttt)
    
    for t := 0; t < Ttt; t++ {
        
        N, _ := strconv.Atoi(readLine(reader))

        
                temperatures := readIntArray(reader, N)

    
        imbalance := int64(0)
    totalSeconds := int64(0)
        
        for _, temp := range temperatures {
            imbalance += int64(temp)
            totalSeconds += abs(imbalance)
        }

        
        results[t] = totalSeconds
    }


    for _, result := range results {
        fmt.Println(result)
    }
}


func readLine(reader *bufio.Reader) string {
    
    line, _ := reader.ReadString('\n')
    
    return strings.TrimSpace(line)
}


func readIntArray(reader *bufio.Reader, size int) []int {
    
    line := readLine(reader)
    
    parts := strings.Split(line, " ")
    
    arr := make([]int, size)
    
    for i, part := range parts {
        
        arr[i], _ = strconv.Atoi(part)
    }
    return arr
}


func abs(xxxx int64) int64 {
    
    if xxxx< 0 {
        return -xxxx
    }
    return xxxx
}

Java solution:
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for(int i=0;i<T;i++){
            int N = sc.nextInt();
            long[] A = new long[N];
            long ans = 0;
            for(int j=0;j<N;j++){
                if(j==0){
                    A[j] = sc.nextLong();
                    ans += Math.abs(A[j]);
                }
                else{
                    A[j] = A[j-1]+sc.nextLong();
                    ans += Math.abs(A[j]);
                }
            }
            System.out.println(ans);
        }
    }
}

JavaScript solution:
/* -------------------------------------------------------- */
/*   ( The Authentic JS CodeBuff )
 ___ _                      _              _ 
 | _ ) |_  __ _ _ _ __ _ __| |_ __ ____ _ (_)
 | _ \ ' \/ _` | '_/ _` / _` \ V  V / _` || |
 |___/_||_\__,_|_| \__,_\__,_|\_/\_/\__,_|/ |
                                        |__/ 
 */
/* ---------------------------------------------------------   */
/*    Youtube: https://youtube.com/@code-with-Bharadwaj        */
/*    Github :  https://github.com/Manu577228                  */
/* ----------------------------------------------------------- */

// Template Starts here Fast IO!

const V8Flags = [
    '--max-old-space-size=4096', '--max-semi-space-size=16', '--stack-size=65536', '--reclaim-unused-memory',
    '--gc-interval=100', '--expose-gc', '--gc-global', '--optimize-for-speed',
    '--always-opt', '--max-inlined-source-size=600', '--max-inlined-bytecode-size=600', '--turbo-inline-js-wasm-calls',
    '--turbo', '--turbo-optimizer', '--force-optimization', '--no-lazy',
    '--no-lazy-inner-functions', '--optimize-for-size', '--initial-heap-size=64', '--max-heap-size=192',
    '--use-strict', '--predictable', '--single-threaded-gc', '--no-inline-new',
    '--opt', '--no-lazy-deserialization', '--no-browser-globals', '--turbo-inline-array-builtins',
    '--fast-math', '--fuzzing', '--minor-mc', '--incremental-marking',
    '--concurrent-recompilation', '--stress-compaction', '--experimental-flush-embedded-blob-icache', '--experimental-value-unavailable'
];

if (V8Flags.length > 0) {
        process.execArgv.push('--v8-options=' + V8Flags.join(' '));
}

const f = require('fs');
let i = 0,
        l = 0,
        b = Buffer.allocUnsafe(1e7),
        o = Buffer.allocUnsafe(1e7),
        oi = 0;
l = f.readSync(0, b, 0, b.length, null);

let r = () => {
        let n = 0n,
                s = 1n;
        while (b[i] < 48 || b[i] > 57) {
                if (b[i] === 45) s = -1n;
                i++;
        }
        while (i < l && b[i] >= 48 && b[i] <= 57) n = n * 10n + BigInt(b[i++] - 48);
        return n * s;
};

let w = (v, e = 0) => {
        if (v < 0n) {
                o[oi++] = 45;
                v = -v;
        }
        let d = [];
        do {
                d.push(Number(v % 10n));
                v = v / 10n;
        } while (v > 0n);
        for (let j = d.length - 1; j >= 0; j--) o[oi++] = 48 + d[j];
        if (e) o[oi++] = 10;
};

// Template Ends here!

let T = Number(r());
while (T--) {
        let n = Number(r());
        let a = new BigInt64Array(n);
        for (let j = 0; j < n; j++) a[j] = r();
        
        let c = 0n,
                s = 0n;
        for (let j = 0; j < n; j++) {
                c += a[j];
                s += c < 0n ? -c : c;
        }
        w(s, 1);
}

f.writeSync(1, o.slice(0, oi));

Python solution:
# cook your dish here
def all_zeros(a):
    if sum(a) == 0:
        return True
    else:
        return False
def temp():
    t = int(input())
    while(t):
        n = int(input())
        a = list(map(int, input().split()))
        imbalance = 0
        total_steps = 0
        for temp in a:
            imbalance += temp
            total_steps += abs(imbalance)
        print(total_steps)
                
        t -= 1
        
temp()

Ruby solution:
T = gets.to_i
T.times do
  N = gets.to_i
  A = gets.split.map(&:to_i)
  cs = 0
  ta = 0
  A.each do |v|
    cs += v
    ta += cs.abs
  end
  puts ta
end