Place Ball Between Pillars
Approach is to check with max left sum and right sum ,the difference between them is the height at which we can hold ball but we are already having pillar of some height so minus height of pillar from the difference
Code :
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=ab.nextInt();
int l=0,r=n-1;
n=0;
int leftsum=0,rightsum=0;
while(l<=r)
{
if(arr[l]<=arr[r])
{
if(arr[l]<leftsum)
{
n+=Math.abs(arr[l]-leftsum);
}
else
{
leftsum=arr[l];
}
l++;
}
else
{
if(arr[r]>rightsum)
{
rightsum=arr[r];
}
else
n+=Math.abs(arr[r]-rightsum);
r--;
}
}
System.out.println(n);
}
}
}
0 Comments:
Post a Comment