Adding Numbers :Victor has an array of size n. He loves to play with these n numbers. Each time he playswith them, he picks up any two consecutive numbers and adds them. On adding both thenumbers, it costs him k*(sum of both numbers).Find the minimum cost of adding all the numbers in the array.Input Specification:input1: Size of array.input2: Elements of the array.input3: Value of k.Output Specification:Return the minimum cost of adding all the numbers of the array.
Answers
Answer:
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define MAXSIZE 6555
int main() {
int n;//size of array
scanf("%i", &n);
int a[MAXSIZE];
for (int i = 0; i < n; i++)
scanf("%i", &a[i]);
int minCost=INT_MAX;
int k;
scanf("%i", &k);
if (n == 1)
return printf("One elements: minimum cost=%i\n", a[0]),0;
for (int i = 0; i < n - 1; i++)
{
if (k * (a[i] + a[i + 1]) < minCost)
minCost = k * (a[i] + a[i + 1]);
}
printf("Minimum cost: = %i\n", minCost);
return 0;
}
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=3;
int arr[n] = {1,2,3};
int k = 2;
int mincost = INT_MAX,sum=0,index,i,temp;
while(n!=1)
{
mincost = INT_MAX;
for(i=1;i<n;i++)
{
if((k*(arr[i]+arr[i-1]))<mincost)
{
temp = arr[i]+arr[i-1];
mincost = k*temp;
index = i;
}
}
if((k*(arr[0] + arr[n-1])) < mincost)
{
temp = arr[0] + arr[n-1];
mincost = k*temp;
arr[0] = temp;
n = n - 1;
}
else
{
arr[index-1] = temp;
for(int j=index;j<n;j++)
{
arr[j] = arr[j+1];
}
n = n - 1;
}
sum = sum + mincost;
}
cout<<sum;
return 0;
}