Skip to main content
11 of 11
Commonmark migration

JavaScript (ES6),  106 104  100 bytes

Saved 2 bytes thanks to @Shaggy

a=>a.filter(n=>n,[...a].map((v,i)=>a[a[p>v&(n=~~a[i+1])<p?k:i+(k=i,n>v&p<n)]+=x=a[i],p=v,i]-=x,p=0))

Try it online!

Commented

We first update the original input array a[] by iterating on a copy of it. During this step, all values 'attracted' by other ones are set to \$0\$.

Because the array is parsed from left to right, we can just add \$a_i\$ to \$a_{i+1}\$ whenever a value is attracted by its right neighbor.

Example: \$4\rightarrow5\rightarrow6\$ is turned into \$[0,\color{red}9,6]\$ and then \$[0,0,\color{red}{15}]\$.

But when several values in a row are attracted by their left neighbor, we need to add \$a_i\$ to the first attractor \$a_k\$ of this sequence (with \$k<i\$) rather than simply \$a_{i-1}\$.

Example: \$6\leftarrow5\leftarrow4\$ is turned into \$[\color{red}{11},0,4]\$ and then \$[\color{red}{15},0,0]\$.

[...a]                 // create a copy of a[]
.map((v, i) =>         // for each value v in a[] at position i:
  a[                   //   this statement updates a[i]:
    a[                 //     this statement updates either a[i] or an adjacent value:
      p > v &          //       if the previous value p is greater than v
      (n = ~~a[i + 1]) //       and the next value n
      < p ?            //       is less than p (attraction to the left):
        k              //         use k (k is initially undefined, but this code cannot
                       //         be triggered during the first iteration)
      :                //       else:
        i + (          //         use either i or i + 1:
          k = i,       //           set k to i
          n > v &      //           use i + 1 if n is greater than v
          p < n        //           and p is less than n (attraction to the right)
        )              //
    ] += x = a[i],     //     add x = a[i] to the entry defined above
    p = v,             //     update the previous value to v
    i                  //     actual index to update a[i]
  ] -= x,              //   subtract x from a[i]
  p = 0                //   start with p = 0
)                      // end of map()

We then filter out all entries equal to \$0\$.

a.filter(n => n)
Arnauld
  • 197.7k
  • 20
  • 179
  • 650