title: Add only distinct elements of an array using a single loop
body: <p>For example: Given an array:</p>
  
  <pre><code>var a = [5,4,3,2,1,4,5,6,7,1];
  </code></pre>
  
  <p>Expected Sum would be: 3+2+6+7 = 18</p>
  
  <p><strong>There should only be a single for loop in the entire code.</strong></p>
  
  <p>My Failed Approach:</p>
  
  <pre><code>var a = [1,1,1,2,2,2,3,4,5,6,7,7,8,2]
  var expected = 3+4+5+6+8
  
  const sum1 = (a) =&gt; {
      var s = 0;
      var ch = {};
      for(let i = 0; i&lt;a.length; i++) {
          if(s &lt;0) {
              s = 0;
          }
          if(ch[a[i]]) {
              s -= a[i]
          } else {
              ch[a[i]] = a[i];
              s += a[i];
          }
      }
  
      return s
  }
  
  console.log(sum1(a))
  </code></pre>