Question: Given an array, find the maximum array distance sum. Array distance sum is defined as below. For any 0 <= p <= q, the array distance is A[p] + A[q] + (q - p)
For example, Given array {0, 2, -1}
A[0][0] = 0, A[0][1] = 3, A[0][2] = 1; A[1][1] = 2 + 2 + (1 - 1) = 4; A[1][2] = 2 + -1 + (2 - 1) = 2. A[2][2] = -1 + -1 + 0 = -2. Thus, the maximum array distance sum is: 4.
If allows extra O(N) memory space, we can do it by allocating an array for (A[p] - p), and another for (A[q] + q). Traverse the two array from front-end and end-front to get the maximum value.
If extra space was required for O(1), we need to analyse the question a bit. The array distance equals to A[p] - p + (A[q] + q). To get the max, we need to get max(A[p] - p) + max(A[q] + q), We can get that the max(A[p] - p) is the peak value in the array. However, max(A[q] + q) might exist after the peak.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int getMaxDistanceSum(vector<int>& array) {
int forwardMax = INT_MIN;
int backwardMax = INT_MIN;
for(int i = 0; i < array.size(); ++i) {
forwardMax = max(forwardMax, array[i] - i);
backwardMax = max(backwardMax, array[i] + i);
}
return forwardMax + backwardMax;
}