Answer to Question #239131 in C# for Vipula

Question #239131
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 the

numbers, 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.
1
Expert's answer
2021-09-19T02:54:08-0400


using System;
using System.Collections.Generic;
namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            int n;//size of array
            Console.Write("Enter size of array: ");
            n = int.Parse(Console.ReadLine());
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
            {
                Console.Write("Enter element of array {0}: ",(i+1));
                a[i] = int.Parse(Console.ReadLine());
            }


            int minCost = int.MaxValue;
            Console.Write("Enter k: ");
            int k = int.Parse(Console.ReadLine());
            if (n == 1)
            {
                Console.WriteLine("Minimum cost: {0}", a[0]);
                return;
            }
            for (int i = 0; i < n - 1; i++)
            {
                if (k * (a[i] + a[i + 1]) < minCost) {
                    minCost = k * (a[i] + a[i + 1]);
                }
            }
            Console.WriteLine("Minimum cost: {0}", minCost);


            Console.ReadLine();
        }
    }
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS