Answer to Question #228278 in Java | JSP | JSF for gagandeep

Question #228278

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.


1
Expert's answer
2021-08-22T00:27:44-0400
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();
	}
}

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