最大化总和,距离整数数组

编程入门 行业动态 更新时间:2024-10-25 11:35:13
本文介绍了最大化总和,距离整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个整型数组A,返回两个元素之间的最大可能的总和距离。总和距离被定义为 A [I] + A [J] +(I - J)对于i>Ĵ

Given an integer array A, return the maximum possible sum-distance between two elements. The sum-distance is defined as A[i] + A[j] + (i - j) for i > j

例如与 A = [8,2,4,9,5,8,0,3,8,2] 最大总和,距离为24取得其中i = 0和j = 8

For example with A = [8, 2, 4, 9, 5, 8, 0, 3, 8, 2] the max sum-distance is 24 achieved with i=0 and j=8

这是O( N 2 )解决方案实在是微不足道。是否有任何O( N )解决方案(其中的 N 是数组的长度)?

An O(n2) solution is trivial. Is there any O(n) solution (where n is the length of the array)?

推荐答案

这是可能的:

  • 创建一个数组,并与A [I]填充+我对每个i

  • Create an array and fill it with A[i]+i for each i

创建另一个数组并用[J]填充 - J对每个j

Create another array and fill it with A[j] - j for each j

获取最高的索引我[MAXI]和J [MAXJ]

Get the indexes with the highest I[maxI] and J[maxJ]

返回A [MAXI] + A [MAXJ] +马克西 - MAXJ

return A[maxI] + A[maxJ] + maxI - maxJ

你去那里,O(N)!

更多推荐

最大化总和,距离整数数组

本文发布于:2023-11-29 18:26:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647230.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   总和   距离

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!