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.
import java.util.Scanner;
public class InputGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("number of elements in the array: ");
int quant = in.nextInt();
int[] arrNum = new int[quant];
int[] arrSumNums = new int[quant-1];
int minNum;
for(int i = 0; i<quant; i++){
System.out.print("Enter " + (i+1) + " number in array: ");
arrNum[i] = in.nextInt();
}
System.out.print("Enter k: ");
int k = in.nextInt();
for( int i = 0; i < quant-1; i++){
arrSumNums[i] = k * (arrNum[i] + arrNum[i+1]);
}
minNum = k * (arrNum[1] + arrNum[quant-1]);
for(int i = 0; i<quant-1; i++){
if(minNum > arrSumNums[i]){
minNum = arrSumNums[i];
}
}
System.out.print("Minimum cost of adding all the numbers of the array: " + minNum);
}
}
Comments
Leave a comment