Maximize (nums[i] - 1) * (nums[j] - 1) over two different indices of an integer array
Company: Samsung
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Overview: Given an array of positive integers, choose two different indices and return the largest possible value of (nums[i] - 1) * (nums[j] - 1). The problem tests reasoning about how a product grows with its factors, handling repeated values at different positions, and writing a single linear scan.
Constraints
- 2 <= nums.length <= 500
- 1 <= nums[i] <= 1000
- i and j must be different indices; the values at those indices may be equal.
- The answer lies between 0 and 998001 (999 * 999), so it never exceeds 2^31 - 1 and a 32-bit int holds it in every language.
Examples
Input: ([3, 4, 5, 2],)
Expected Output: 12
Explanation: Source example 1: values 4 and 5 give 3 * 4 = 12, and every other pair gives 8 or less.
Input: ([1, 5, 4, 5],)
Expected Output: 16
Explanation: Source example 2: the maximum 5 sits at two different indices, so both copies count: 4 * 4 = 16.
Hints
- Every value is at least 1, so each factor nums[i] - 1 is zero or positive. Think about how a product of two non-negative numbers changes as either factor grows.
- The two indices must differ, yet the same value can appear at two indices and both copies may be used.
- Check your idea by hand on [3, 4, 5, 2] (answer 12) and [1, 5, 4, 5] (answer 16).