702815. Minimize the sum of product

Easy

Minimize the sum of product

Summary

We are given an array arr and two integers n and m. We need to find the minimum sum of products that we can get by choosing n elements from the array, each of which will be multiplied by some integer. The goal is to minimize this sum.

The key concepts involved in this problem are arrays, greedy, sorting, data structures, and algorithms.

Detailed Explanation

To solve this problem, we first sort the array in ascending order. Then, we initialize two variables min_sum and max_product. We iterate over the array from left to right, considering each element as a candidate for multiplication. For each element, we calculate its product with the next n-1 elements (since we need to choose n elements in total). We keep track of the maximum product found so far (max_product) and the minimum sum that can be achieved using this product (min_sum). The minimum sum is updated if the current sum is less than min_sum. Finally, we return min_sum.

Here's a step-by-step breakdown of the solution:

  1. Sort the array in ascending order.
  2. Initialize min_sum and max_product.
  3. Iterate over the array from left to right:
    • For each element, calculate its product with the next n-1 elements.
    • Update max_product if the current product is greater than max_product.
    • Calculate the sum of products using max_product.
    • Update min_sum if the current sum is less than min_sum.
  4. Return min_sum.

Time complexity: O(n log n) due to sorting. Space complexity: O(1) as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int minimizeSumOfProduct(int[] arr, int n, int m) {
    Arrays.sort(arr);
    int min_sum = Integer.MAX_VALUE;
    for (int i = 0; i < arr.length - n + 1; i++) {
        int max_product = 1;
        for (int j = i; j < i + n; j++) {
            max_product *= arr[j];
        }
        min_sum = Math.min(min_sum, max_product * (arr[i + n - 1] - arr[i]));
    }
    return min_sum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.