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 <algorithm>
#include <iostream>
#include <map>
int main() {
int n; int m;
std::cin >> n >> m;
using val_type = long long;
std::map<int,val_type> map;
while(m--){
val_type start, end, val;
std::cin >> start >> end >> val;
map[start] += val;
map[end+1] -= val;
}
val_type max{0};
val_type partial_sum{0};
for (const auto& el : map) {
partial_sum += el.second;
if (partial_sum > max) {
max = partial_sum;
}
}
std::cout << 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?
n
is not used at all in computing the answer. I hope you have enough theoretical basis in comping up with the algorithm for computing the answer. \$\endgroup\$