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
The task contradicts itself, so I made 2 programs for each of the cases.
For max:
import java.util.Arrays;
import java.util.Scanner;
public class Answer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int n = scanner.nextInt();
int[] a = new int[n];
System.out.println("Enter elements of array: ");
for (int i = 0; i < a.length; i++){
a[i] = scanner.nextInt();
}
int minCost = Integer.MIN_VALUE;
System.out.println("Enter value of K: ");
int k = scanner.nextInt();
if (n == 1) {
System.out.println("One elements: minimum cost" + a[0]);
}
for (int i = 0; i < a.length - 1; i++) {
int i1 = k * (a[i] + a[i + 1]);
if (i1 > minCost)
minCost = i1;
}
System.out.println("Max cost: = " + minCost);
}
}
For min
import java.util.Scanner;
public class Answer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int n = scanner.nextInt();
int[] a = new int[n];
System.out.println("Enter elements of array: ");
for (int i = 0; i < a.length; i++){
a[i] = scanner.nextInt();
}
int minCost = Integer.MAX_VALUE;
System.out.println("Enter value of K: ");
int k = scanner.nextInt();
if (n == 1) {
System.out.println("One elements: minimum cost" + a[0]);
}
for (int i = 0; i < n - 1; i++) {
int i1 = k * (a[i] + a[i + 1]);
if (i1 < minCost)
minCost = i1;
}
System.out.println("Minimum cost: = " + minCost);
}
}
Comments
Leave a comment