Sequence with sum K and minimum sum of absolute differences between consecutive elements
Last Updated :
12 Jul, 2022
Given two integers N and K, the task is to find a sequence of integers of length N such that the sum of all the elements of the sequence is K and the sum of absolute differences between all consecutive elements is minimum. Print this minimized sum.
Examples:
Input: N = 3, K = 56
Output: 1
The sequence is {19, 19, 18} and the sum of absolute
differences of all the consecutive elements is
|19 – 19| + |19 – 18| = 0 + 1 = 1 which is the minimum possible.
Input: N = 12, K = 48
Output: 0
The sequence is {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}.
Approach: There can be two cases:
- When K % N = 0 then the answer will be 0 as K can be evenly divided into N parts i.e. every element of the sequence will be equal.
- When K % N != 0 then the answer will be 1 because the sequence can be arranged in a way:
- (K – (K % N)) is divisible by N so it can be divided evenly among all the N parts.
- And the rest (K % N) value can be divided in such a way to minimize the consecutive absolute difference i.e. add 1 to the first or the last (K % N) elements and the sequence will be of the type {x, x, x, x, y, y, y, y, y} yielding the minimum sum as 1.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int minimum_sum( int n, int k)
{
if (k % n == 0)
return 0;
return 1;
}
int main()
{
int n = 3, k = 56;
cout << minimum_sum(n, k);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int minimum_sum( int n, int k)
{
if (k % n == 0 )
return 0 ;
return 1 ;
}
public static void main (String[] args)
{
int n = 3 , k = 56 ;
System.out.println (minimum_sum(n, k));
}
}
|
Python3
def minimum_sum(n, k):
if (k % n = = 0 ):
return 0 ;
return 1
n = 3
k = 56
print (minimum_sum(n, k))
|
C#
using System;
class GFG
{
static int minimum_sum( int n, int k)
{
if (k % n == 0)
return 0;
return 1;
}
static public void Main ()
{
int n = 3, k = 56;
Console.Write(minimum_sum(n, k));
}
}
|
Javascript
<script>
function minimum_sum(n, k)
{
if (k % n == 0)
return 0;
return 1;
}
let n = 3, k = 56;
document.write(minimum_sum(n, k));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...