Bob 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 number). Find the minimum cost of adding all the numbers in the array.
import java.util.Scanner;
public class FindMinimumCostInArray {
static int findMinimumCost(int array[]) {
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for (int j = 0; j < array.length; j++) {
if (array[j] < min1)
{
min2 = min1;
min1 = array[j];
}
else if ((array[j] < min2) && array[j] != min1) {
min2 = array[j];
}
}
return (min2 + min1);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of array: ");
int size = input.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter element "+(i+1)+": ");
array[i] = input.nextInt();
}
System.out.println("Minimum sum is " + findMinimumCost(array));
input.close();
}
}
Comments
Leave a comment