Java Online Compiler
Example: Minimum Operations to Equalize Array Elements (Brute-Force Approach) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Minimum Operations to Equalize Array Elements (Brute-Force Approach) import java.util.Arrays; // Required for toString and for min/max helper // Main class containing the entry point of the program public class Main { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = {1, 10, 2, 9}; System.out.println("Array: " + Arrays.toString(arr1) + ", Min Operations (Brute-Force): " + minOperationsBruteForce(arr1)); // Expected: 2 System.out.println("Array: " + Arrays.toString(arr2) + ", Min Operations (Brute-Force): " + minOperationsBruteForce(arr2)); // Expected: 16 } // Method to calculate minimum operations using brute force public static long minOperationsBruteForce(int[] arr) { if (arr == null || arr.length <= 1) { return 0; } // Step 1: Find the minimum and maximum values in the array int minVal = arr[0]; int maxVal = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < minVal) { minVal = arr[i]; } if (arr[i] > maxVal) { maxVal = arr[i]; } } // Step 2: Initialize minimum operations to a very large value long overallMinOperations = Long.MAX_VALUE; // Step 3: Iterate through all possible target values from minVal to maxVal for (int target = minVal; target <= maxVal; target++) { long currentOperations = 0; // Step 3a: Calculate operations for the current target for (int num : arr) { currentOperations += Math.abs(num - target); } // Step 3b: Update overall minimum if current target yields fewer operations if (currentOperations < overallMinOperations) { overallMinOperations = currentOperations; } } // Step 4: Return the overall minimum operations found return overallMinOperations; } }
Output
Clear
ADVERTISEMENTS