using System.Collections.Generic;
using System.Collections;
public static void Main()
List<int> pw = new List<int>() {20,13,8,9};
long a = getHeaviestPackage(pw);
List<int> pw1 = new List<int>() {1,2,3};
long a1 = getTotalImbalance(pw1);
public static long getHeaviestPackage(List<int> packageWeights) {
Stack<long> stack = new Stack<long>();
for (int i = packageWeights.Count - 1; i >= 0; i--) {
long cur = packageWeights[i];
while ((stack.Count != 0) && cur < stack.Peek()) {
while (stack.Count != 0) {
res = Math.Max(res, stack.Pop());
public static long getTotalImbalance(List<int> weight) {
Stack<int> stack = new Stack<int>();
for (int i = 0; i <= weight.Count; i++) {
while ((stack.Count != 0) && (i == weight.Count || weight[(stack.Peek())] > weight[i])) {
int leftB = (stack.Count == 0) ? -1 : stack.Peek();
res -= (long) (i - cur) * (cur - leftB) * weight[cur];
for (int i = 0; i <= weight.Count; i++) {
while ((stack.Count != 0) && (i == weight.Count || weight[(stack.Peek())] < weight[i])) {
int leftB = (stack.Count == 0) ? -1 : stack.Peek();
res += (long) (i - cur) * (cur - leftB) * weight[cur];