Having an array A of integers with N elements for example {4, 2, 11, -2, 1} i need to find the element with max value from every sub array . Sub arrays are generated this way:
for i = 0, leftArray = {4} , rightArry = {2,11,-2,1}
for i = 1, leftArray = {4,2}, rightArry = {11,-2,1}
for i = 2, leftArray = {4,2,11}, rightArry = {-2, 1}
for i = 3, leftArray = {4,2,11,-2}, rightArry {1}
So, i need something like this:
for (int i = 0; i < A.length; i++){
//LOGIC HERE
System.err.println(String.format("Left array max = %s, Right array max = %s",lmax, rmax));
}
This would't be a problem if we don't care about time-complexity, BUT expected worst-case time complexity is O(N)
I have not idea how to achive this with O(N) algorithm. Any help would be appreciated.
EDIT:
My current solution:
for (int i = 0; i < A.length; i++)
{
if(i == A.length - 1)
break;
int[] l = Arrays.copyOfRange(A, 0, i + 1);
int[] r = Arrays.copyOfRange(A, i + 1, A.length);
Arrays.sort(l);
Arrays.sort(r);
System.err.println(l[l.length -1] + " " + r[r.length - 1]);
}
ito get the max forleftArray, then a loop with descendingito get the max forrightArray.O(n)is stillO(n).