I am unable to clear testcase 6,7 and 8. It says my code is too slow for these test cases.
This is my code:
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for(int i =0;i<n;i++){
arr[i]=scn.nextInt();
}
int water_total = 0;
for(int i = 1;i<n-1;i++){
int lmax = maxleftarray(arr,i-1);
int rmax = maxrightarray(arr,i+1);
if(lmax>rmax && rmax-arr[i]>=0){
int water_in_this_block = rmax-arr[i];
water_total = water_total + water_in_this_block;
}else if(rmax>lmax && lmax-arr[i]>=0){
int water_in_this_block = lmax-arr[i];
water_total = water_total + water_in_this_block;
}else if(rmax==lmax && lmax-arr[i]>=0){
int water_in_this_block = lmax-arr[i];
water_total = water_total + water_in_this_block;
}
}
System.out.print(water_total);
}
public static int maxleftarray(int[] arr,int hi){
int lmax = arr[0];
for(int i = 0;i<=hi;i++){
if(arr[i]>lmax){
lmax = arr[i];
}
}
return lmax;
}
public static int maxrightarray(int[] arr,int lo){
int rmax = arr[lo];
for(int i = lo;i<=arr.length-1;i++){
if(arr[i]>rmax){
rmax = arr[i];
}
}
return rmax;
}
}
How can i optimize my code to clear all the test cases?