FastPrepMinimize Adjacent Squared-Difference Cost with One Insertion

Minimize Adjacent Squared-Difference Cost with One Insertion

Microsoft logoMicrosoftMediumINTERNOA
Learn

Problem statement

The cost of an integer array is the sum of (values[i]-values[i-1])^2 for every adjacent pair.

Insert exactly one integer anywhere, including either end, and return the minimum possible cost. The inserted integer may be any signed 32-bit value.

Function

minimumSquaredDifferenceCost(values: int[]) → long

Examples

Example 1

values = [1,5]return = 8

Inserting 3 changes the cost from 16 to 8.

Example 2

values = [1,2,3]return = 2

Every adjacent gap is one, so insertion cannot reduce the cost.

Example 3

values = []return = 0

Inserting into an empty array leaves no adjacent pair.

Constraints

  • 0 <= values.length <= 100000.
  • -10^9 <= values[i] <= 10^9.
  • The answer fits in a signed 64-bit integer.

More Microsoft problems

See Microsoft hiring insights
public long minimumSquaredDifferenceCost(int[] values) {
    // write your code here
}
values[1,5]
expected8
Checking account…