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:
- Initialize a variable
costto keep track of the total cost. - Iterate over the list and for each element, calculate the difference between the element and 1 (abs(element - 1)).
- Add this difference to the
cost. - 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
public int minCostToMakeSize1(int[] arr) {
int cost = 0;
for (int num : arr) {
cost += Math.abs(num - 1);
}
return cost;
}