878829. Min Cost to Make Size 1

Easy

Min Cost to Make Size 1

Summary

Given a list of integers, find the minimum cost to make all sizes equal to 1. The cost is calculated by summing up the absolute difference between each element and 1.

Detailed Explanation

To solve this problem, we will iterate over the list and calculate the total cost. For each element, we subtract or add 1 depending on whether it's greater than or less than 1 to make its size equal to 1. The total cost is then calculated as the sum of absolute differences.

Here is a step-by-step breakdown:

  1. Initialize a variable cost to keep track of the total cost.
  2. Iterate over the list and for each element, calculate the difference between the element and 1 (abs(element - 1)).
  3. Add this difference to the cost.
  4. Return the cost.

Time complexity: O(n), where n is the size of the input list.

Space complexity: O(1), as we only use a constant amount of space to store the cost variable.

Optimized Solutions

Java

View on GeeksforGeeks
public int minCostToMakeSize1(int[] arr) {
    int cost = 0;
    for (int num : arr) {
        cost += Math.abs(num - 1);
    }
    return cost;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.