I was presented with an interview question described as follows:
Receiving an int[] A
of cities, where each A[i]
has an appeal value. We want to plan our trip based on the highest appeal possible, taking in mind that is calculated as follows A[i] + A[j] + (i - j)
. This means the appeal values of 2 cities summed, plus their distance.
Function signature:
public static int solution(int[] A);
The constraints were the following:
- N is an integer within [1, 100,000]
- A[i] is an integer within [-1,000,000,000, 1,000,000,000]
Using the same value is a possible valid solution, so for example, if we have A = {1, 3, -3};
this should return 6
as visiting city A[0]
twice gives the max appeal value A[0] + A[0] + (0 - 0) = 6
.
So given that, a possible solution is the same value twice, I did not found other solution than:
int highestAppeal = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
int currentAppeal = A[i] + A[j] + (i - j);
highestAppeal = currentAppeal > highestAppeal ? currentAppeal : highestAppeal;
}
}
return highestAppeal;
This solution was marked as pretty bad. I realize that a \$O(n^2)\$ solution is far from efficient, but in this case, I did not see how to improve it. Later on, I thought about sorting A
values in descending order and, for repeated values, using indexes in ascending order. But I don't see that going forward.
What would be a better and more efficient solution for this?
int
is expected as result. \$\endgroup\$