2
\$\begingroup\$

I got a programming question on an interview where performance was the focus. I couldnt come up with a better solution than the one below which I think has a time complexity of O(n^2 + n) and scored 20/100 on performance.

The question in short was to find the highest result by adding two elements and in an array and the difference between the two indices e.g A[k] + A[j] + (j - k) - (k can be equal to j).

The size of the array = [1...100 000]
The values in the array =[-1000 000 000...1000 000 000]

I know using nested loops usally is a bad idea when It comes to handling larger arrays. So my question is simply how can it be improved to make it faster?

public static int solution(int [] A) {
 Set<Integer> occoured = new HashSet<Integer>();
 int maxAppeal = 0;
 for(int i = 0; i < A.length; i++) {
 if(occoured.add(A[i])) {
 for(int j = i; j < A.length; j++) {
 int appeal = A[i] + A[j] + (j - i);
 if(appeal > maxAppeal)
 maxAppeal = appeal;
 }
 }
 }
 return maxAppeal;
}
vnp
58.6k4 gold badges55 silver badges144 bronze badges
asked Jan 10, 2019 at 15:14
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

This is not a review, but an extended comment.

Consider the question:

Given two arrays, A and B, find the maximum of A[i] + B[j]

I suppose you can do it in linear time.

Now rearrange the original equation as (A[k] - k) + (A[j] + j) and consider two auxiliary arrays, formed by A[i] - i and A[i] + i.

Finally realize that you don't need these arrays at all.

answered Jan 10, 2019 at 17:44
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.