Suppose there is an array A = {3,2,5}
, then points for this array correspond to indexes (i,j)
where i <= j = {(0,0), (0,1), (0,2), (1,1), (1,2), (2,2)}
. The program returns max(sum)
such that sum = A[i] + A[j] + (j - i)
. For the above array :
- point
(0,0)
will havesum = (3 + 3) + (0 - 0) = 6
- point
(0,1)
will havesum = (3 + 2) + (1 - 0) = 6
- point
(0,2)
will havesum = (3 + 5) + (2 - 0) = 10
- point
(1,1)
will havesum = (2 + 2) + (0 - 0) = 4
- point
(1,2)
will havesum = (2 + 5) + (2 - 1) = 8
- point
(2,2)
will havesum = (5 + 5) + (2 - 2) = 10
Therefore program should return max(sum) = 10
I have solved this problem, but I'm struggling to reduce the complexity of the solution to O(n). Is there a more elegant, efficient way to this?
static int solution(int[] arr) {
//when array is empty
if(arr.length == 0) {
return 0;
}
//when array is of length 1
if(arr.length == 1) {
return 2*arr[0];
}
List<Integer> list1 = new ArrayList<Integer>();
for(int i=0;i<arr.length;i++) {
list1.add(arr[i]);
}
//copy old list to new one and sort the new one
List<Integer> list2 = new ArrayList<Integer>(list1);
Collections.sort(list2);
//replace values to indexes using 1st list
for(int i=0;i<list2.size();i++) {
list2.add(i,list1.indexOf(list2.remove(i)));
}
//sort old list. Now my 1st list contains sorted values, and 2nd one contains corresponding old indexes
Collections.sort(list1);
int i = list1.size()-1;
//set max to point (n-1,n-1)
int max = 2*list1.get(i);
while(i > 0) {
int j = 1;
while(j < i) {
int sum = (list1.get(i) + list1.get(i-j)) + (list2.get(i) -list2.get(i-j));
if(sum > max) {
max = sum;
}
j++;
}
i--;
}
return max;
}
a
andb
indexes or values of array elements? \$\endgroup\$O(n)
is possible? The number of "points" is(n*n/2)
already. \$\endgroup\${ 10, 0, 10 }
when the correct answer is 22. \$\endgroup\$