Problem · Array

Get Minimum Cost

Learn this problem
MediumIBM logoIBMFULLTIMEOA
See IBM hiring insights

Problem statement

For an integer array arr, define its cost as:

Σ (arr[x] - arr[x + 1])^2 for every index 0 ≤ x < arr.length - 1.

Insert exactly one integer at any position in the array. Return the minimum possible cost after the insertion.

Function

getMinimumCost(arr: int[]) → long

Examples

Example 1

arr = [1, 3, 5, 2, 10]return = 49

The original cost is 81. Insert 6 between 2 and 10. That edge contributes (2 - 6)^2 + (6 - 10)^2 = 32 instead of (2 - 10)^2 = 64, so the total becomes 49.

Constraints

  • 2 ≤ arr.length ≤ 10^4
  • 1 ≤ arr[i] ≤ 10^5

More IBM problems

drafts saved locally
public long getMinimumCost(int[] arr) {
    // Write your code here
}
arr[1, 3, 5, 2, 10]
expected49
checking account