Minimize Adjacent Squared-Difference Cost with One Insertion
Problem statement
You are given an array arr of n positive integers, indexed from 0.
The cost of an array is the sum of squared differences between adjacent elements:
cost(arr) = sum((arr[i] - arr[i - 1])^2) for i from 1 through arr.length - 1.
Insert exactly one integer at any position in the array, including the beginning or the end, so that the resulting cost is minimized.
Return the minimum possible cost after this insertion.
Function
minimumSquaredDifferenceCost(arr: int[]) → longExamples
Example 1
arr = [1,3,5,2,10]return = 49The original cost is (1 - 3)^2 + (3 - 5)^2 + (5 - 2)^2 + (2 - 10)^2 = 81.
Two possible insertions are:
- Insert
4between3and5. The cost becomes(1 - 3)^2 + (3 - 4)^2 + (4 - 5)^2 + (5 - 2)^2 + (2 - 10)^2 = 79. - Insert
6between2and10. The cost becomes(1 - 3)^2 + (3 - 5)^2 + (5 - 2)^2 + (2 - 6)^2 + (6 - 10)^2 = 49.
The minimum possible cost is 49.
Constraints
2 <= arr.length <= 10^41 <= arr[i] <= 10^5