Angry Children 2
Difficulty: Hard

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]$.


Output Format:
A single integer representing the minimum achievable unfairness sum.

**Sample Input 0**  

	7
    3
    10
    100
    300
    200
    1000
    20
    30

**Sample Output 0**  

	40

**Explanation 0**

Bill Gates will choose packets having 10, 20 and 30 candies.  The unfairness sum is $|10-20| + |20-30| + |10-30| = 40$.  

**Sample Input 1**  

    10
    4
    1
    2
    3
    4
    10
    20
    30
    40
    100
    200

**Sample Output 1**  

    10

**Explanation 1**  

Bill Gates will choose 4 packets having 1,2,3 and 4 candies. The unfairness sum i $|1-2| + |1-3| + |1-4| + |2-3| + |2-4| + |3-4| = 10$.


Sample Input:

Sample Output:

Python 3 starter code:
#
# Complete the 'angryChildren' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. INTEGER k
#  2. INTEGER_ARRAY packets
#

def angryChildren(k, packets):
    # Write your code here



Editorial: Angry Children 2 : Oct 2020 Editorial
<style id="MathJax_SVG_styles">.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%}
.MathJax_SVG .MJX-monospace {font-family: monospace}
.MathJax_SVG .MJX-sans-serif {font-family: sans-serif}
.MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0}
.MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none}
.mjx-svg-href {fill: blue; stroke: blue}
.MathJax_SVG_LineBox {display: table!important}
.MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
</style><svg style="display: none;"><defs id="MathJax_SVG_glyphs"></defs></svg><p><a href="https://www.hackerrank.com/contests/oct13/challenges/angry-children-2">Angry Children 2</a></p>

<p>Choose K out of N elements of an array, following the given constraints. Read the complete problem statement <a href="https://www.hackerrank.com/contests/oct13/challenges/angry-children-2">here</a>   </p>

<p><strong>Difficulty Level</strong></p>

<p>Medium</p>

<p><strong>Required Knowledge</strong></p>

<p>Sorting, Easy Dynammic Progamming</p>

<p><strong>Time Complexity</strong></p>

<p>O(NlogN)</p>

<p><strong>Approach</strong></p>

<p>In this problem, we are given a list of N numbers out of which K numbers are to be chosen such that the anger coefficient is minimized. </p>

<p>Let us define D as the anger-coefficient of chosen K numbers.</p>

<p>First, we claim that k such numbers can only be obtained if we sort the list and chose k contiguous numbers. This can easily be proved. Suppose we choose numbers X<sub>1</sub>, X<sub>2</sub>, X<sub>3</sub>,....X<sub>r</sub>, X<sub>r+1</sub>,....,X<sub>K</sub> (all are in increasing order but not continuous in the sorted list) i.e. there exists a number p which lies between X<sub>r</sub> and X<sub>r+1</sub>.Now, if we include p and drop X<sub>1</sub>, our anger coefficient will decrease by an amount = </p>

<p>( |X<sub>1</sub> - X<sub>2</sub>| + |X<sub>1</sub> - X<sub>3</sub>| + .... + |X<sub>1</sub> - X<sub>K</sub>| ) - ( |p - X<sub>2</sub>| + |p - X<sub>3</sub>| + .... + |p - X<sub>K</sub>| )</p>

<p>which is certainly positive. This shows that the solution will consist of k continues elements of the sorted list. Now there exists (N-K+1) such sets of elements. The problem can be redefined as to find the minimum of the D obtained from all these sets.  </p>

<p>First, we sort the list in increasing order: X<sub>1</sub>, X<sub>2</sub>, X<sub>3</sub>,....X<sub>K</sub>,X<sub>K+1</sub>,....,X<sub>N</sub>. The next step is to find the value of D for the first K elements i.e. from X<sub>1</sub> to X<sub>K</sub>. suppose we have calculated D for first i elements. when we include X<sub>i+1</sub>, the value of D increases by ( |X<sub>i+1</sub> - X<sub>1</sub>| + |X<sub>i+1</sub> - X<sub>2</sub>| +....+ |X<sub>i+1</sub> - X<sub>i</sub>| ), which in turn is equal to ( i*X<sub>K</sub> - (X<sub>1</sub> + X<sub>2</sub> + ....+X<sub>i</sub>) ). We just need to store the sum of current elements and repeat the step for i = 1 to k-1.</p>

<p>Now that we have the solution for X<sub>1</sub> to X<sub>K</sub>, we would want to calculate the same for  X<sub>2</sub> to X<sub>K+1</sub>. This can be done in O(1) time.</p>

<p>New anger coefficient = old anger coefficient + ( |X<sub>K+1</sub> - X<sub>2</sub>| + |X<sub>K+1</sub> - X<sub>3</sub>| + .... + |X<sub>K+1</sub> - X<sub>K</sub>| ) - ( |X<sub>1</sub> - X<sub>2</sub>| + |X<sub>1</sub> - X<sub>3</sub>| + .... + |X<sub>1</sub> - X<sub>K</sub>| ). This can be written in the following form:</p>

<p>New anger coefficient = old anger coefficient + K.(X<sub>K</sub> - X<sub>1</sub>) - K.(X<sub>1</sub> + X<sub>2</sub> +....+X<sub>K</sub>) + ( X<sub>1</sub> - X<sub>K</sub>)</p>

<p>At every point we just need to update the sum of the K elements, calculate the new anger co-efficient and update the minimum value of the same. </p>

<p><strong>Setter's Code</strong> :</p>

<pre><code>n = input()
k = input()
assert 1 &lt;= n &lt;= 10**5
assert 1 &lt;= k &lt;= n

lis = []
for i in range(n):
    lis.append(input())

lis.sort()
sum_lis = []
for i in lis:
    assert 0 &lt;= i &lt;= 10**9

val = 1-k
answer = 0

sum_lis.append(lis[0])

for i in range(1,n):
    sum_lis.append(sum_lis[i-1]+lis[i])

for i in range(k):
    answer += val*lis[i]
    val += 2

final_answer = answer
for i in range(k,n):
    new_answer = answer + (k-1)*lis[i] + (k-1)*lis[i-k] - 2*(sum_lis[i-1]-sum_lis[i-k])
    final_answer = min(new_answer, final_answer)
    answer = new_answer

print final_answer
</code></pre>

<p><strong>Tester's Code</strong> :</p>

<pre><code>#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;
#include&lt;algorithm&gt;
#include&lt;assert.h&gt;
using namespace std;
#define Max_N 100001
typedef long long int ll;
long long int sum[Max_N];
int N,K,input[Max_N];
ll min(ll a,ll b)
{
    if(a&gt;b)    return b;
    else return a;
}
int main()
{
    int val;
    scanf("%d%d",&amp;N,&amp;K);
    assert(1&lt;=N &amp;&amp; N&lt;=100000);
    assert(1&lt;=K &amp;&amp; K&lt;=N);
    for(int i=1;i&lt;=N;i++)
    {
        scanf("%d",&amp;input[i]);
        assert(0&lt;=input[i] &amp;&amp; input[i]&lt;=1000000000);
    }
    input[0]=0;
    sort(input+1,input+N+1);
    sum[0]=0;
    for(int i=1;i&lt;=N;i++)    sum[i]=input[i]+sum[i-1];

    val=1-K;
    ll answer=0,compare,previous;
    for(int i=1;i&lt;=K;i++){
        answer+=(ll)val*input[i];
        val+=2;
    }
    //printf("%lld is answeer\n",answer);
    previous=answer;
    for(int i=K+1;i&lt;=N;i++){
        compare=(ll)(K-1)*input[i];
        compare=previous + (ll)(K-1)*input[i] + (ll)(K-1)*input[i-K]-(ll)2*(sum[i-1]-sum[i-K]);
        answer=min(answer,compare);
        previous=compare;
    }
    printf("%lld\n",answer);
    return 0;
}
</code></pre>

Reference solution (Python):
###Python 2  
```python  
n = input()
k = input()
assert 1 <= n <= 10**5
assert 1 <= k <= n
    
lis = []
for i in range(n):
    lis.append(input())
    
lis.sort()
sum_lis = []
for i in lis:
    assert 0 <= i <= 10**9
    
val = 1-k
answer = 0
    
sum_lis.append(lis[0])
    
for i in range(1,n):
    sum_lis.append(sum_lis[i-1]+lis[i])
    
for i in range(k):
    answer += val*lis[i]
    val += 2
    
final_answer = answer
for i in range(k,n):
    new_answer = answer + (k-1)*lis[i] + (k-1)*lis[i-k] - 2*(sum_lis[i-1]-sum_lis[i-k])
    final_answer = min(new_answer, final_answer)
    answer = new_answer
    
print final_answer
```