700283. Largest product

Basic

Largest Product

Summary

Given a list of integers, find the largest product that can be obtained by multiplying any number of elements from the list. This problem requires an understanding of arrays and data structures.

Detailed Explanation

To solve this problem, we will iterate over all possible pairs of numbers in the list, multiply them together, and keep track of the maximum product found so far. We will also consider the case where a single element is the largest product.

Here's the step-by-step breakdown:

  1. Initialize two variables: max_product to store the maximum product found so far, and current_product to store the product of the current pair of numbers.
  2. Iterate over the list of integers using two nested loops (one for each number in the list).
  3. For each pair of numbers, multiply them together and update current_product.
  4. If current_product is greater than max_product, update max_product with the new value.
  5. After iterating over all pairs of numbers, return max_product.

Time complexity analysis: The time complexity is O(n^2), where n is the size of the input list, because we are iterating over each pair of numbers in the list.

Space complexity analysis: The space complexity is O(1), as we only need a constant amount of space to store the maximum product and current product variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int largestProduct(int[] arr) {
    int max_product = arr[0];
    int current_product = arr[0];

    for (int i = 1; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            current_product = arr[i] * arr[j];
            if (current_product > max_product) {
                max_product = current_product;
            }
        }
    }

    return max_product;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.