10)adding numbers
Victor has an array of size n.He loves to play with these n numbers.each time he plays with them ,he picks up any two consecutive numbers and adds them. on adding both numbers,it costs him K*(sum of both numbers).
Find the minimum cost of adding all the numbers in the array.
i/p1:size of array
i/p2:elements of array
i/p3:value of K
o/p:return the maximum cost of adding all the numbers of the array.
Ex1:
i/p1:3
i/p2:{1,2,3}
i/p3:2
o/p:18
explanation: There are multiple ways of adding the numbers of an array.
The first way is:1+2=3 cost of adding is 2*3=6.
3+3=6 cost ofadding is 2*6=12
o/p: there are other ways as well,but minimum cost is 18
ex2:
i/p1:4
i/p2:{4,5,6,7}
i/p3:3
o/p:132
explanation:
for minimum cost ,
4+5=9 cost of adding is 3*9=27
6+7=13 cost of adding is 3*13=39
9+13=cost of adding is 3*22=66
Therefore cost is 27+39+66=132
#include <stdio.h>
int main()
{
int i, n, K, sum, cost;
printf("Enter size of array: ");
scanf("%d", &n);
int array[n];
printf("Enter elements of array:\n");
for (i=0; i<n; i++)
scanf("%d", &array[i]);
printf("Enter value of K: ");
scanf("%d", &K);
sum = 0;
cost = 0;
for (i=0; i<n; i=i+2)
{
if ((i+1) < n)
{
sum = sum + array[i];
sum = sum + array[i+1];
cost = cost + sum * K;
}
sum = 0;
}
for (i=0; i<n; i++)
sum = sum + array[i];
cost = cost + sum * K;
printf("\nCost: %d\n", cost);
return 0;
}
Comments
Leave a comment