CIRCULAR ARRAY ROTATION - (RIGHT)
Approach : We have no need to do any shifts here,just an index arithmetic is enough i.e.,
for (int i = 0; i < n; i++) {
scanf("%d",&a[(i+k)%n]); }
while reading the values itself !!!!
ARRAY LEFT ROTATION
Approach : Same here, just an index arithmetic and it can be done in 2 ways :
1.with additional array :
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
b[(n-d+i)%n] = a[i];
}
2.with no additional array : (cool :p)
where d = # of left rotations
int l = n-d;
for(int i=0;i<n;i++){
if(l == n)
l = 0;
scanf("%d",&a[l++]);}
********************************BOMB OF THE DAY*******************************
ARRAY MANIPULATION
Approach : If we follow naive approach or any most efficient sorting algorithm you will still get TLE. So, I discovered something called a "prefix sum" (in the editorial of course :p)
Here, instead of updating m (queries) times, we update the l(add) and r+1(subtract) indices only and while finding the max. value in array, we keep on adding the values in the array [?]till we encounter
-ve value[?]
NAIVE - FAILED - TLE
for(long a0 = 0; a0 < m; a0++){
long a,b,k;
scanf("%ld %ld %ld", &a, &b, &k);
a--;
b--;
for(int i=a;i<=b;i++)
ar[i] = ar[i] + k;}
//used even merge sort
//still failed
WORKING - (PREFIX SUM)
editorial link : https://www.hackerrank.com/challenges/crush/editorial (but still didn't understood :p)
for(i=0;i<k;i++){
long long int l,r,k;
scanf("%lld %lld %lld",&l,&r,&k);
a[l] = a[l] + k;
if(r+1<=n){
a[r+1] = a[r+1] - k;}
}
for(i=1;i<=n;i++){
x = x + a[i];
if(max<x){
max=x; }
}
printf("%lld",max);
That's it !!!!! Need to get my head around it.
No comments:
Post a Comment