Maximum sum of two elements in an array minus the distance between them

ぐ巨炮叔叔 提交于 2021-02-19 23:09:14

问题


I am trying to find the maximum sum of two elements in an array minus the distance between them. Specifically I am trying to calculate max{ a[i]+a[j]-|i-j| } I am currently stuck. I have obviously considered the naive approach (O(n^2)). However ,I am pretty sure there is a better ,more efficient approach (O(nlogn)) or even O(n). Can someone please help me on how to approach the problem. I would be grateful if anyone threw some hints or a simple idea to have something to start from. Sorting the array first? Maybe using a dynamic programming approach?

Edit: I think I have found an O(n) solution Let's assume that our max sum comes from a[i] and a[j] , a[i] contributes to that sum with : a[i]+i . a[j] contributes to that sum with a[j]-j. (Because our sum is a[i]+a[j]-|j-i|= a[i]+a[j]+i-j. ) Approach: for convenience we compute the matrices A_plus_index=a[i]+i and A_minus_index=a[i]-i. Then we use two helping arrays: i) The first one has for every i ,the max value of A_plus_index array considering only the elements from 0 to i. ii) The second has for every i, the max value of A_minus_index array considering only the elements from N to i ,where N is the length of array a. Now we traverse the arrays once and find the max: A_plus_index[i]+ A_minus_index[i+1]. Total complexity O(n).


回答1:


@JeffersonWhite your idea works and you could post it as an answer and accept it.

But I am going to improve upon your idea a little bit:

You could build only one array instead of 2, which contains the maximum of A[j] - j so far for each j from N-1 to 1.

And then traverse the array forward each time computing the max( A[i] + i + max_so_far-_reverse[i+1])

//Building the reverse array
max_so_far_reverse = array of length N
max_reverse = A[N-1]-(N-1)
max_so_far_reverse[N-1] = max_reverse
for j = N-2 to 1:
   max_reverse = max(max_reverse, A[j]-j)
   max_so_far_reverse[j] = max_reverse

//Computing maximum value by traversing forward
max = 0
for i = 0 to N-2:
    max = max(max, A[i] + i + max_so_far_reverse[i+1])

return max


来源:https://stackoverflow.com/questions/60591517/maximum-sum-of-two-elements-in-an-array-minus-the-distance-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!