Answer to Question #335362 in Java | JSP | JSF for mahesh

Question #335362

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


1
Expert's answer
2022-05-04T17:40:02-0400

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);
        
    }
}

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