HackerRank - Array Manipulation - Follow-up This is a follow-up question for HackerRank - Array Manipulation


  Problem
  
  You are given a list (1-indexed) of size \$n\$, initialized with zeroes.
  You have to perform \$m\$ operations on the list and output the maximum of
  final values of all the  elements in the list. For every operation,
  you are given three integers \$a\$, \$b\$ and \$k\$ and you have to add value
  \$k\$ to all the elements ranging from index \$a\$ to \$b\$ (both inclusive).
  
  Example input

5 3
1 2 100
2 5 100
3 4 100

  
  Expected output

200

  
  Explanation
  
  After first update list will be:

100 100 0 0 0

  
  After second update list will be:

100 200 100 100 100

  
  After third update list will be:

100 200 200 200 100

  
  So the required answer will be: 200


Final solution

I changed the way of storing the values, which now get indexed into a map. I think now it's efficient in time and space, my main questions left are about style (taking into account the impositions of the hacker rank input output).

#include &lt;algorithm&gt;
#include &lt;iostream&gt;
#include &lt;map&gt;

int main() {
    int n; int m;
    std::cin &gt;&gt; n &gt;&gt; m;
    using val_type = long long;
    std::map&lt;int,val_type&gt; map;
    while(m--){
        val_type start, end, val;
        std::cin &gt;&gt; start &gt;&gt; end &gt;&gt; val;
        map[start] += val;
        map[end+1] -= val;
    }
    val_type max{0};
    val_type partial_sum{0};
    for (const auto&amp; el : map) {
        partial_sum += el.second;
        if (partial_sum &gt; max) {
            max = partial_sum;
        }
    }
    std::cout &lt;&lt; max;
    return 0;
}


I don't like for example that I need to declare the variable partial_sum outside the for loop, being in the same scope as max. Any idea on how to write this partial sum to find the max cleaner?
Whitespace, let your code breathe

Your code has a few logical sections, you should use empty lines to break them appart visually. It makes your code easier to read.

Personal opinion: front-load your type aliases

General wisdom in C++ is to define things as close as possible to their first use, but that's generally meant for objects with lifetimes. I personally prefer to put any type alias at the start of its scope.

algorithm is unused, so it should not be included

Simple enough: do not #include stuff you don't need.

That's kind of it, really, good job!

Edit: to answer your question, you could finagle something with std::accumulate, or just create a scope for partial_sum, but it's not worth the trouble. What you have it fine.