该题解利用数学方法和几何思想来求解问题。首先,它调整 index 位置,确保 index 靠近右边界,这样可以简化问题的对称性。接下来,它计算左右两侧的三角形区域的和,这些区域代表了如果中心点逐渐增加,周围元素需要按照最大差1的规则增加所需的最小总和。题解主要分为三种情况处理:1) 完美金字塔型,其中中心元素到两边的差值可以自由变化而不受边界限制;2) 右边界受限,左侧可以自由增加;3) 两侧都受到边界的限制。每种情况下,都通过数学公式来计算可能的最大中心值,同时注意到总和的限制。最后,根据计算得到的额外可用和分配给数组元素,来确定最终的最大值。
时间复杂度: O(1)
空间复杂度: O(1)
class Solution:
def maxValue(self, n: int, index: int, maxSum: int) -> int:
maxSum -= n # 将所有元素初始化为1,减去这些基础值
if index < n // 2: # 如果index在左半边,则转到右半边以简化问题
index = n - index - 1
n_left = index # index左边的元素数
n_right = n - 1 - index # index右边的元素数
tri_left = (n_left * (n_left + 1)) // 2 # 左侧最大增长和,不触及边界
tri_right = (n_right * (n_right + 1)) // 2 # 右侧最大增长和,不触及边界
# 情况1:理想金字塔形
if maxSum <= (tri_right * 2 + n_right + 1):
return int(math.sqrt(maxSum)) + 1
# 情况2:右侧触及边界
if maxSum <= (tri_left + tri_right + (n_left - n_right) * n_right + n_left + 1):
b = 3 + 2 * n_right
return int((-b + math.sqrt(b * b - 8 * (tri_right + 1 - n_right * n_right - maxSum))) / 2) + 1 + 1
# 情况3:两侧都触边界
maxSum -= (tri_left + tri_right + (n_left - n_right) * n_right + n_left + 1)
return n_left + 1 + 1 + (maxSum // n)