Open In App

Minimum possible value of Summation of |A[i] – A[i+K]|

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers and an integer K, the task is to find the minimum possible value of summation of |A[i] – A[i+K]| for any permutation of array arr[] (for all the indices from 0 to N – K – 1)

Examples:

Input: N = 4, arr = {1, 2, 3, 4}, K = 2
Output: 2
Explanation: For the permutation {1, 3, 2, 4}, for i = 0 the value of | A[0] – A[2] | = 1 and for i = 1 the value of | A[1] – A[3] | = 1. So the answer is 1+1 = 2.

Input: N = 6, arr = {1, 1, 2, 4, 5, 6}, K = 3
Output: 3
Explanation: For the permutation {1, 2, 5, 1, 4, 6}, for i = 0 the value of | A[0] – A[3] | = 0 and for i = 1 the value of | A[1] – A[4] | = 2 and for i = 2 the value of | A[2] – A[5] | = 1 and the answer is 
0 + 1 + 2 = 3.

Approach: To solve the problem follow the below steps:

  • For finding this we have to find the answer for different permutations of the array
  • So first of all we have to find every permutation and then find the answer for that and take minimum.
  • For finding all the permutations of the array we can use the STL function next_permutaion() which will give us all the permutations of the array one by one.
  • For each permutation, we will compute the answer and take the minimum of all.

Below is the implementation of the above approach:

C++

// C++ Code for the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to get minimum value
int getMin(int N, int K, vector<int>& arr)
{

    // Variable to store answer
    int ans = INT_MAX;

    // Loop to get every permutation
    do {

        // Variable to store value for
        // current permutation
        int temp = 0;

        // Iterating over array
        for (int i = 0; i < N - K; i++) {
            temp += abs(arr[i] - arr[i + K]);
        }

        // Taking minimum value into answer
        ans = min(ans, temp);
    } while (next_permutation(arr.begin(), arr.end()));

    return ans;
}

// Drivers code
int main()
{

    // Size and value of K
    int N = 4, K = 2;

    // Array
    vector<int> arr = { 1, 2, 3, 4 };

    // Calling function to get minimum value
    cout << getMin(N, K, arr);
    return 0;
}

Python3

# python Code for the above approach

import sys

# Function to get minimum value
def getMin(N, K, arr):
    ans = sys.maxsize

    # Variable to store answer
    arr = list(arr)
    
    # Loop to get every permutation
    while (next_permutation(arr)):
      
          # Variable to store value for
        # current permutation
        temp = 0
        
        # Iterating over array
        for i in range(N - K):
            temp += abs(arr[i] - arr[i + K])
            
        # Taking minimum value into answer
        ans = min(ans, temp)

    return ans
  
# function to check if next permutation exist or not
def next_permutation(arr):
    n = len(arr)
    i = n - 2
    while i >= 0 and arr[i] >= arr[i + 1]:
        i -= 1
    if i == -1:
        return False
    j = i + 1
    while j < n and arr[j] > arr[i]:
        j += 1
    j -= 1
    arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1:] = arr[i + 1:][::-1]
    return True

#driver code

# Size and value of K
N = 4
K = 2
arr = [1, 2, 3, 4]

# Calling function to get minimum value
print(getMin(N, K, arr))

Java

// Java Code for the above approach

import java.io.*;
import java.util.*;

class GFG {

    // Function to get minimum value
    static int getMin(int N, int K, int[] arr)
    {

        // Variable to store answer
        int ans = Integer.MAX_VALUE;

        do {

            // Variable to store value for
            // current permutation
            int temp = 0;

            // Iterating over array
            for (int i = 0; i < N - K; i++) {
                temp += Math.abs(arr[i] - arr[i + K]);
            }

            // Taking minimum value into answer
            ans = Math.min(ans, temp);
        } while (nextPermutation(arr));

        return ans;
    }

    // nextPermutation function
    static boolean nextPermutation(int[] arr)
    {
        int i = arr.length - 2;
        while (i >= 0 && arr[i] >= arr[i + 1]) {
            i--;
        }
        if (i < 0) {
            return false;
        }
        int j = arr.length - 1;
        while (arr[j] <= arr[i]) {
            j--;
        }
        swap(arr, i, j);
        reverse(arr, i + 1);
        return true;
    }

    // Function to reverse elements in array
    static void reverse(int[] arr, int start)
    {
        int end = arr.length - 1;
        while (start < end) {
            swap(arr, start, end);
            start++;
            end--;
        }
    }

    // Function to swap two numbers.
    static void swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args)
    {
        // Size and value of K
        int N = 4, K = 2;

        // Array
        int[] arr = { 1, 2, 3, 4 };

        // Calling function to get minimum value
        System.out.println(getMin(N, K, arr));
    }
}

// This code is contributed by karthik.

C#

// C# Code for the above approach
using System;

public class GFG{

    // Function to get minimum value
    static int getMin(int N, int K, int[] arr)
    {

        // Variable to store answer
        int ans = Int32.MaxValue;

        do {

            // Variable to store value for
            // current permutation
            int temp = 0;

            // Iterating over array
            for (int i = 0; i < N - K; i++) {
                temp += Math.Abs(arr[i] - arr[i + K]);
            }

            // Taking minimum value into answer
            ans = Math.Min(ans, temp);
        } while (nextPermutation(arr));

        return ans;
    }

    // nextPermutation function
    static bool nextPermutation(int[] arr)
    {
        int i = arr.Length - 2;
        while (i >= 0 && arr[i] >= arr[i + 1]) {
            i--;
        }
        if (i < 0) {
            return false;
        }
        int j = arr.Length - 1;
        while (arr[j] <= arr[i]) {
            j--;
        }
        swap(arr, i, j);
        reverse(arr, i + 1);
        return true;
    }

    // Function to reverse elements in array
    static void reverse(int[] arr, int start)
    {
        int end = arr.Length - 1;
        while (start < end) {
            swap(arr, start, end);
            start++;
            end--;
        }
    }

    // Function to swaap two numbers.
    static void swap(int[] arr, int i, int j)
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    static public void Main (){

        // Size and value of K
        int N = 4, K = 2;

        // Array
        int[] arr = { 1, 2, 3, 4 };

        // Calling function to get minimum value
        Console.WriteLine(getMin(N, K, arr));
    }
}

Javascript

// Javascript code for the above approach

// Function to get minimum value
function getMin(N, K, arr) {

    // Variable to store answer
    let ans = Number.MAX_SAFE_INTEGER;

    // Loop to get every permutation
    do {

        // Variable to store value for
        // current permutation
        let temp = 0;

        // Iterating over array
        for (let i = 0; i < N - K; i++) {
            temp += Math.abs(arr[i] - arr[i + K]);
        }

        // Taking minimum value into answer
        ans = Math.min(ans, temp);
    } while (next_permutation(arr));

    return ans;
}

// Helper function to get next permutation
function next_permutation(arr) {

    // Find non-increasing suffix
    let i = arr.length - 1;
    while (i > 0 && arr[i - 1] >= arr[i])
        i--;

    if (i <= 0)
        return false;

    // Find successor to pivot
    let j = arr.length - 1;
    while (arr[j] <= arr[i - 1])
        j--;

    let temp = arr[i - 1];
    arr[i - 1] = arr[j];
    arr[j] = temp;

    // Reverse suffix
    j = arr.length - 1;
    while (i < j) {
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        i++;
        j--;
    }

    return true;
}

// Driver code
function main() {

    // Size and value of K
    let N = 4, K = 2;

    // Array
    let arr = [1, 2, 3, 4];

    // Calling function to get minimum value
    console.log(getMin(N, K, arr));
}

main();

// this code is contributed by bhardwajji

Output

2

Time Complexity: O(N*N*N!)
Auxiliary Space: O(1)



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads