0

Click here to view the source of the problem

Given an array 'A' consisting of 'n' integers, It is required to find the maximum value of the following expression:

            |Ai - Aj| + |i - j|

where Ai is an element of the array at the i-th position( 0-indexed array)

I could only come up with an O(n^2) solution. Which includes fixing upon an element and iterating over the rest of the array while constantly updating the maximum value.

What could be a faster approach to the above problem?

hackncrack
  • 11
  • 5

1 Answers1

1

This problem basically involves finding the largest and smallest values. Heres a O(n) solution

Heres the hand math of how this works.

You get the values one by one

1 2 3 1

and you know the indexes of these values

0 1 2 3

if you add them together, you get

1 3 5 4

if you keep track of the lowest sum at the lowest index and highest sums at the highest index, those points will be the values you need to use

for(int i = 0; i < N; i++)
{
    int value = 0;
    scanf("%d", value);
    if(value + i < min.total) // < gets the lowest indexed value
    {
        min.total = value + i;
        min.value = value;
        min.index = i;
    }
    if(value + i >= max.total) // >= gets the highest indexed value
    {
        max.total = value + i;
        max.value = value;
        max.index = i;
    }
}
int output = abs(max.value - min.value) + abs(max.index - min.index);

- Edit I organized the array values with this simple struct

struct ArrayVal {
    int index;
    int value;
    int total;
};

- Edit 2 Per @ViduhVerma's keen eyes, I make the following edit.

instead of summing the indexes, subtract them.

Example 1:

input numbers:   10 5 15 18 11 4
input indexes:   0  1  2  3  4 5
resulting subs: 10 4 13 15  7 -1
max - min = 16 

Example 2:

input numbers:   1 2 3 1
input indexes:   0 1 2 3
resulting subs:  1 1 1 -2
max - min = 3
Henri
  • 145
  • 13