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 :



title-img


                            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

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →