Answer to Question #254556 in Java | JSP | JSF for Shwetha T P

Question #254556
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.

Please give java coding for this question.
Please
1
Expert's answer
2021-10-21T05:21:11-0400
import java.util.Scanner;

public class FindMinimumCostOfAdding {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		int arrSize = in.nextInt();
		int[] numbers = new int[arrSize];
		for (int i = 0; i < arrSize; i++) {
			numbers[i] = in.nextInt();
		}
		int k = in.nextInt();
		
		in.close();
		
		//sort
		int min, minI;
		for (int b = 0; b < arrSize; b++) {
			min = numbers[b];
			minI = b;
			for (int cur = b + 1; cur < arrSize; cur++) {
				if (numbers[cur] < min) {
					min = numbers[cur];
					minI = cur;
				}
			}
			int tmp = numbers[b];
			numbers[b] = min;
			numbers[minI] = tmp;
		}
		
		//calculate
		int result = 0, sum;
		for (int b = 0; b < arrSize - 1; b++) {
			sum = numbers[b] + numbers[b + 1];
			result += k * sum;
			numbers[b + 1] = sum;
		}
		
		System.out.println(result);
	}
}

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
New on Blog
APPROVED BY CLIENTS