Equal Stacks

  • + 0 comments

    Imagine you have a pointer which always point to the smallest one. and try to remove the next one until it becomes the smallest. then repeat.

    function equalStacks(h1: number[], h2: number[], h3: number[]): number {
        let a = [h1, h2, h3]
        let s = a.map(x => x.reduce((a, b) => a + b, 0))
        let smallest = s[0];
        let smallestIndex = 0;
        for (let i = 0; i < a.length; i++) {
            if (s[i] < smallest) {
                smallest = s[i]
                smallestIndex = i
            }
        }
        
        while(!s.every(x => x == s[0])) {
            let i = (smallestIndex + 1) % a.length;
            while (s[i] > smallest) {
                s[i] -= a[i].shift()
                if (a[i].length == 0) {
                    return 0;
                }
            }
            if (s[i] <= smallest) {
                smallest = s[i];
                smallestIndex = i
            }
        }
        
        return smallest;
    }