Solving C programming

 PROBLEM IN C PROGRAMMING

QUESTION:

        You are a wizard who possesses a magic wand that can be used to change the values of an array. Your wand has two powers: Increase and Decrease. With each use of the wand, you can either increase or decrease any element of the array by 1. One day, a group of villagers came to you with a problem. They had an array of positive integers of size N and a set of queries of size M. For each query, queries[i], they wanted to make all the elements of the array equal to queries[i] using your magic wand. To help the villagers, you decided to use your magic wand to perform the operations. However, each time you perform an operation, the cost of using your wand increases. The cost of using your wand for an operation on an element is equal to the absolute difference between the value of the element and the desired value after the operation. Example: If you want to change an element from 5 to 3, it will cost you 2. If you want to change an element from 7 to 8, it will cost you 1. You can perform any number of operations on any element of the array for a given query. However, the cost of using the wand for each operation accumulates, and you want to minimize the total cost of all operations for each query.


CODING: 

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,m;
    scanf("%d %d",&n, &m);
    int arr[n], query[m];
    for(int i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    for(int t=0;t<m;t++)
    {
        scanf("%d",&query[t]);
    }
    int cost[m];
    for(int i=0;i<m;i++)
    {
         cost[i]=0;
        for(int t=0;t<n;t++)
        {
               cost[i]+= abs (query[i]-arr[t]);
        }
        printf("%d ",cost[i]);
    }
}

INPUT:
5 3
1 3 2 4 5
5 2 1

OUTPUT:
10 7 10

LINK:

IMAGES:


LOGICAL EXPLANATION:




Comments