Problem · Array

Minimum Cost to Convert Products to Variant A

Learn this problem
MediumAmazon logoAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

An inventory array product contains only 0 and 1, where 0 represents variant A and 1 represents variant B.

In one operation, choose a subarray of length k. The cost of that operation is the sum of the values inside the chosen subarray. Then choose one index inside that subarray whose value is 1 and change it to 0.

Return the minimum total cost needed to convert every product to variant A.

Function

minCostToConvertAllToVariantA(product: int[], k: int) → int

Complete the function minCostToConvertAllToVariantA in the editor below.

minCostToConvertAllToVariantA has the following parameters:

  1. int[] product: the product variants
  2. int k: the fixed operation window length

Returns

int: the minimum total cost.

Examples

Example 1

product = [1, 1, 1]k = 2return = 4

Use window [0, 1] twice, then window [1, 2] once. The costs are 2 + 1 + 1 = 4.

Example 2

product = [1, 0, 1]k = 2return = 2

Choose the left window once to clear the first 1, and the right window once to clear the last 1.

Constraints

  • product[i] is either 0 or 1
  • 1 <= k <= product.length
  • Each operation must change exactly one 1 inside the chosen window to 0.

More Amazon problems

drafts saved locally
public int minCostToConvertAllToVariantA(int[] product, int k) {
    // write your code here
}
product[1, 1, 1]
k2
expected4
checking account