Angry Children 2
Problem Statement :
Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has brought a box of packets of candies and would like to distribute one packet to each of the children. Each of the packets contains a number of candies. He wants to minimize the cumulative difference in the number of candies in the packets he hands out. This is called the unfairness sum. Determine the minimum unfairness sum achievable. For example, he brings n = 7 packets where the number of candies is packets = [3,3,4,5,7,9,10]. There are k=3 children. The minimum difference between all packets can be had with 3,3,4 from indices 0,1 and 2. We must get the difference in the following pairs: {(0,1),(0,2),(1,2)}. We calculate the unfairness sum as: packets candies 0 3 indices difference result 1 3 (0,1),(0,2) |3-3| + |3-4| 1 2 4 (1,2) |3-4| 1 Total = 2 Function Description Complete the angryChildren function in the editor below. It should return an integer that represents the minimum unfairness sum achievable. angryChildren has the following parameter(s): k: an integer that represents the number of children packets: an array of integers that represent the number of candies in each packet Input Format The first line contains an integer n. The second line contains an integer k. Each of the next n lines contains an integer packets[i]. Constraints 2 <= n <=10^5 2 <= k <= n 0 <= packets[i] <= 10^9 Output Format A single integer representing the minimum achievable unfairness sum.
Solution :
Solution in C :
In c++ :
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 100005;
long long a[N], sum[N];
long long s(int a, int b) { return sum[b] - (a ? sum[a - 1] : 0LL); }
int main()
{
//freopen("test.in", "r", stdin);
int n, k;
scanf("%i %i", &n, &k);
for(int i = 0; i < n; i++)
scanf("%lld", &a[i]);
sort(a, a + n);
sum[0] = a[0];
for(int i = 1; i < n; i++)
sum[i] = sum[i - 1] + a[i];
long long curr = 0;
for(int i = 0; i < k; i++)
curr += (long long)(2 * i + 1) * a[i];
long long res = curr;
for(int i = 0; i + k - 1 < n; i++)
{
res = min(res, curr - k * s(i, i + k - 1));
curr -= a[i] + 2LL * s(i + 1, i + k - 1);
curr += (long long)(2 * k - 1) * a[i + k];
}
printf("%lld\n", res);
return 0;
}
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static long curTime;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), k = in.nextInt();
long[] x = new long[n];
for(int i = 0; i < n; i++) x[i] = in.nextInt();
Arrays.sort(x);
curTime = System.currentTimeMillis();
System.out.println(f(n, k, x));
}
private static long f(int n, int k, long[] x){
long t = unFair(k, x), min = t, s = 0;
//long s = sum(1, k-1, x);
for(int i = 1; i < k; i++) s += x[i];
for(int i = 1; i + k-1 < x.length; i++){
//System.out.println(t);
t += (k-1)*(x[i-1] + x[i+k-1]);
t -= 2*s;
if(t < min) min = t;
s += x[i+k-1] -x[i];
}
return min;
}
private static long unFair(int k, long[] x){
long s = 0;
for(int i = 0; i < k; i++){
s += x[i] *(2*i-k+1);
}
return s;
}
private static long sum(int i, int j, long[] x){
long s = 0;
for(int k = i; k <= j; k++) s += x[k];
return s;
}
/*private static long aSum(int i, int j, long[] x){
if(i == j) return x[i];
return x[j] - aSum(i, j-1, x);
}*/
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long long int min(long long int a,long long int b){
if(a<b)
return a;
return b;
}
int cmpr(const void * a,const void *b){
return (*(long long int *)a)-(*(long long int *)b);
}
int main(){
long long int n,k,i=0,j;
scanf("%lld %lld",&n,&k);
long long int a[n];
while (i<n) {
scanf("%lld",&a[i]);
i++;
}
qsort(a, n, sizeof(long long int), cmpr);
i=0;
j=1-k;
long long int sum=0,sum1=0;
while(i<k){
sum+=a[i]*j;
sum1+=a[i];
j+=2;
i++;
}
i=0;
j=k;
long long int ans=sum;
while (j<n) {
sum1-=a[i];
sum=sum-(2*sum1)-((1-k)*a[i])+(k-1)*a[j];
sum1+=a[j];
ans=min(ans,sum);
i++;
j++;
}
printf("%lld\n",ans);
return 0;
}
In Python3 :
n = int(input())
k = int(input())
a = []
for i in range(n):
a.append(int(input()))
a.sort()
ps = [0]
for i in range(n):
ps.append(ps[-1] + a[i])
cur = 0
for i in range(k):
cur += i * a[i] - ps[i]
ans = cur
for i in range(1, n - k + 1):
cur -= ps[i + k - 1] - ps[i - 1] - k * a[i - 1]
cur += k * a[i + k - 1] - ps[i + k] + ps[i]
ans = min(ans, cur)
print(ans)
View More Similar Problems
The Strange Function
One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting
View Solution →Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →