Starting with a 1-indexed array of zeros and a list of operations, for each operation, I have to add value to each of the array elements between two given indices, inclusive. Once all operations have been performed, I have to return the maximum value in the array. But the wrong answer is coming every time for most test cases and for some test cases time limit is exceeding. Kindly help me to solve this problem.
I am using arrayManipulation function to get the number of array elements and queries array. And update function is used to update(add the element) the array.
import java.util.*;
import java.util.Arrays;
public class sample
{
public static void main(String args[])
{
int maximum=0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int queries[][]=new int[m][3];
for(int x=0;x<m;x++)
{
for(int y=0;y<3;y++)
{
queries[x][y]=sc.nextInt();
}
}
maximum=arrayManipulation(n,queries);
System.out.println(maximum);
}
public static int arrayManipulation(int num,int qry[][])
{
int a=0,b=0,k=0;
int max=Integer.MIN_VALUE;
int arr[]=new int[num];
int arr2[]=new int[num];
for(int i=0;i<num;i++)
{
arr[i]=0;
}
for(int j=0;j<qry.length;j++)
{
for(int kl=0;kl<qry[0].length;kl++)
{
a=qry[j][kl];
b=qry[j][kl+1];
k=qry[j][kl+2];
break;
}
arr2=update(a,b,k,arr);
int lengtharr2=arr2.length;
max=Math.max(max,arr2[lengtharr2-1]);
}
return max;
}
public static int[] update(int a1,int b1, int k1,int array[])
{
for(int i=a1;i<b1;i++)
{
array[i]+=k1;
}
Arrays.sort(array);
return array;
}
}
Input: 10 means the number of array elements and 3 is no. of queries which consist of a,b,k values which mean like this: the left index, right index, and summand
10 3
1 5 3
4 8 7
6 9 1
My output:
11
expected output:
10