Problem 1913

Abstract / Summary

Given four numbers pick two with the highest product and two with the lowest product to find the maximum difference between these products.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1913.py

class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()
        return nums[-1] * nums[-2] - nums[0] * nums[1]
4 lines | 155 bytes | submitted December 18, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 83% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method maxProductDifference. The method receives a list of integers, sorts the list in place, and then computes the difference between the product of the two largest numbers and the product of the two smallest numbers. The result is returned as an integer.

Key Steps

The algorithm proceeds through three distinct operations:

The first operation sorts the input list:

nums.sort()

Sorting arranges the elements in non-decreasing order, guaranteeing that the smallest values occupy the first positions and the largest values occupy the last positions.

The second operation extracts the two largest elements using negative indexing:

largest_product = nums[-1] * nums[-2]

Negative indices refer to elements counted from the end of the list, so nums[-1] is the maximum value and nums[-2] is the second-maximum value after sorting.

The third operation extracts the two smallest elements using standard forward indexing:

smallest_product = nums[0] * nums[1]

Index 0 points to the minimum value and index 1 points to the second-minimum value.

Finally, the method returns the difference between the two products:

return largest_product - smallest_product

Edge Cases

Because the list is sorted before any arithmetic is performed, the method correctly handles several edge conditions:

When the list contains duplicate values, sorting preserves their relative order, and the same value may appear in both the largest and smallest positions. The multiplication steps still produce valid products, and the subtraction yields the correct difference.

If the list includes negative numbers, sorting places the most negative values at the beginning and the most positive values at the end. The product of two negative numbers becomes positive, and the algorithm naturally accounts for this when computing largest_product and smallest_product. The subtraction therefore reflects the true product difference even when sign changes are involved.

When the list length is exactly four, which is the minimal size required to have two distinct smallest and two distinct largest elements, the algorithm still functions correctly because the indices 0, 1, -2, and -1 are all valid. The method does not rely on any extra elements beyond these four positions.

Performance Optimizations

The implementation leverages the in-place sort method, which avoids allocating an additional list for ordering. By sorting the original list, memory overhead is minimized. The subsequent product calculations use direct indexing without any loops or auxiliary data structures, resulting in constant-time arithmetic after the sort completes. This straightforward approach eliminates the need for multiple passes over the data, keeping the overall execution path concise and efficient.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a box full of number cards. The goal is to find the biggest ones and the smallest ones. First, the code picks up all the cards and lines them up from the smallest number on the left to the biggest number on the right. Once they are in a nice, neat row, it grabs the two biggest cards from the very end of the line and multiplies them together to see how giant that product is. Then, it grabs the two smallest cards from the beginning of the line and multiplies them together to see how tiny that product is. Finally, it takes the giant number and subtracts the tiny number to see the big difference between them.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.85 | σ = 1.20

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ JS Java Go
Progiez Python C++ Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
suxrobGM C#
varunu28 Java
27 links | 16 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 medium
2 solutions   December 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality