Maximum array distance Sum

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值