Equal Stacks

  • + 0 comments

    Typescript solution with a map. Can work with any count of incoming arrays

     
    function equalStacks(h1: number[], h2: number[], h3: number[]): number {
        let maxHeight:number = 0;
        let mapSimilar: Record<number, number> = {}
        let initArrays = [h1, h2, h3];
        function sumArray(values: number[]) { 
          let prev = 0;
          let value= 0;
          for(let i= values.length -1; i>=0; i--) {
            value= prev + values[i];
            if(!mapSimilar[value]) {
              mapSimilar[value] = 0;
            }
            mapSimilar[value]++;
            prev = value;
          } 
        }
        initArrays.forEach((subArray) => sumArray(subArray));
        for(const key in mapSimilar) {
          if(mapSimilar[key] === initArrays.length) {
            maxHeight = Math.max(maxHeight,  parseInt(key))
          }
        }
        return maxHeight;
    }