CSES Solutions - Stick Lengths
Last Updated :
15 Mar, 2024
There are N sticks with some lengths given by arr[]. Your task is to modify the sticks so that each stick has the same length. You can either lengthen or shorten each stick. Both operations cost X where X is the difference between the new and original length. What is the minimum total cost?
Examples:
Input: N = 5, arr[] = {2, 3, 1, 5, 2}
Output: 5
Explanation: We can make all the sticks of length = 2. The total cost = abs(2 - 2) + abs(3 - 2) + abs(1 - 2) + abs(5 - 2) + abs(2 -2) = 0 + 1 + 1 + 3 + 0= 5.
Input: N = 5, arr[] = {1, 1, 1, 1, 1}
Output: 0
Explanation: All the sticks already have the same length. The total cost = 0.
Approach: To solve the problem, follow the below idea:
Think geometrically. Assume that array elements are co-ordinates on X axis. The problem reduces to finding another co-ordinate such that the sum of distances between this choice and other co-ordinate is minimized.
Observe that: If number of coordinates are odd then Y = middle element. If even then Y is any number in between middle 2 co-ordinates. Say Input = [a, b, c, d]. Output is any number between b and c including both. Hence the cost is sum which can be computed easily now that we have chosen Y. sum|(Y-arr[i])| for all i.
Step-by-step algorithm:
- Sort the array arr[] in ascending order.
- Find the median as the middle element of the array arr[].
- Iterate over the array and find the absolute difference between arr[i] and the median.
- Sum of all these differences will be our answer.
Below is the implementation of the algorithm:
C++
#include <bits/stdc++.h>
using namespace std;
// method to calculate the minimum total cost
long long calculateStickLength(int* arr, int N)
{
// sort the array to find the median
sort(arr, arr + N);
int median = arr[N / 2];
long long ans = 0;
// Find the cost of individual stick
for (int i = 0; i < N; i++) {
ans += abs(median - arr[i]);
}
return ans;
}
int main()
{
// Sample Input
int N = 5;
int arr[] = { 2, 3, 1, 5, 2 };
cout << calculateStickLength(arr, N) << "\n";
return 0;
}
Java
import java.util.*;
public class StickLength {
// Method to calculate the minimum total cost
static long calculateStickLength(int[] arr, int N)
{
// Sort the array to find the median
Arrays.sort(arr);
int median = arr[N / 2];
long ans = 0;
// Find the cost of individual stick
for (int i = 0; i < N; i++) {
ans += Math.abs(median - arr[i]);
}
return ans;
}
public static void main(String[] args)
{
// Sample Input
int N = 5;
int[] arr = { 2, 3, 1, 5, 2 };
System.out.println(calculateStickLength(arr, N));
}
}
// This code is contributed by akshitaguprzj3
C#
using System;
class Program
{
// Method to calculate the minimum total cost
static long CalculateStickLength(int[] arr)
{
// Sort the array to find the median
Array.Sort(arr);
int median = arr[arr.Length / 2];
long ans = 0;
// Find the cost of individual stick
foreach (int num in arr)
{
ans += Math.Abs(median - num);
}
return ans;
}
static void Main(string[] args)
{
// Sample Input
int[] arr = { 2, 3, 1, 5, 2 };
Console.WriteLine(CalculateStickLength(arr));
}
}
JavaScript
// Method to calculate the minimum total cost
function calculateStickLength(arr) {
// Sort the array to find the median
arr.sort((a, b) => a - b);
const median = arr[Math.floor(arr.length / 2)];
let ans = 0;
// Find the cost of individual stick
for (let i = 0; i < arr.length; i++) {
ans += Math.abs(median - arr[i]);
}
return ans;
}
// Sample Input
const N = 5;
const arr = [2, 3, 1, 5, 2];
console.log(calculateStickLength(arr));
Python3
def calculate_stick_length(arr):
# Sort the array to find the median
arr.sort()
median = arr[len(arr) // 2]
ans = 0
# Find the cost of individual stick
for length in arr:
ans += abs(median - length)
return ans
# Driver code
if __name__ == "__main__":
# Sample Input
arr = [2, 3, 1, 5, 2]
print(calculate_stick_length(arr))
Time Complexity: O(N* logN), where N is the number of sticks.
Auxiliary Space: O(1)
Similar Reads
Foundation CSS Sticky Foundation CSS is an open-source & responsive front-end framework built by the ZURB foundation in September 2011, which makes it easy to design beautiful responsive websites, apps, and emails that look amazing & can be accessible to any device. The framework is built on SaaS-like bootstrap.
9 min read
Foundation CSS Stick to bottom Foundation CSS is an open-source & responsive front-end framework built by the ZURB foundation in September 2011, which makes it easy to design beautiful responsive websites, apps, and emails that look amazing & can be accessible to any device. The framework is built on SaaS-like bootstrap.
8 min read
Foundation CSS Kitchen Sink Sticky Foundation CSS is an open-source and responsive front-end framework built by the ZURB foundation in September 2011, which makes it easy to design beautiful responsive websites, apps, and emails that look amazing and can be accessible to any device. The framework is built on SaaS-like bootstrap. It i
6 min read
Semantic-UI Sticky Examples Semantic UI Sticky content remains fixed to the browser viewport until another content on the viewport is visible. Semantic UI also offers configurations that allow us to control the scroll direction of the sticky content, and determine the parent viewport or the oversized content. Syntax: $('.ui.st
2 min read
CSS | Length Data Type Length is the measurement of distance followed by a length unit. There is no space between the number and unit. It can be positive or negative. The length unit is optional after 0. There are two types of length units which are absolute and relative. Lengths are used in many CSS properties, such as p
2 min read