HackerRank: Algorithmic Crush
You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, 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).
private void run() throws Exception {
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n = nextInt();
int m = nextInt();
long[] a = new long[n + 1];
for (int i = 0; i < m; i++) {
int l = nextInt() - 1;
int r = nextInt();
int v = nextInt();
a[l] += v;
a[r] -= v;
}
long cur = 0;
long max = 0;
for (int i = 0; i < n; i++) {
cur += a[i];
max = Math.max(max, cur);
}
System.out.println(max);
}
private int nextInt() throws Exception {
st.nextToken();
return (int) st.nval;
}
You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, 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).
int main()
{
long long int N,M,i,k;
cin>>N>>M;
assert(3<=N);
assert(N<=10000000);
assert(1<=M);
assert(M<=200000);
vector < pair<long long int , long long int > > V;
for(i=1 ; i<=M ; i++)
{
long long int a,b;
cin>>a>>b>>k;
V.push_back(make_pair(a,k));
V.push_back(make_pair(b,(-1)*k));
}
sort(V.begin(), V.end(), compare);
for(i=0 ; i<2*M; i++)
A[i] = V[i].second;
for(i=1 ; i<2*M ; i++)
A[i] = A[i-1]+A[i];
sort(A,A+2*M);
cout<<A[2*M -1]<<endl;
return 0;
}
https://codepair.hackerrank.com/paper/tbNo0s9Z?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9private void run() throws Exception {
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n = nextInt();
int m = nextInt();
long[] a = new long[n + 1];
for (int i = 0; i < m; i++) {
int l = nextInt() - 1;
int r = nextInt();
int v = nextInt();
a[l] += v;
a[r] -= v;
}
long cur = 0;
long max = 0;
for (int i = 0; i < n; i++) {
cur += a[i];
max = Math.max(max, cur);
}
System.out.println(max);
}
private int nextInt() throws Exception {
st.nextToken();
return (int) st.nval;
}