Taro Logo

Maximum Product of First and Last Elements of a Subsequence

#1 Most AskedMedium
3 views
Topics:
ArraysGreedy Algorithms

You are given an integer array nums and an integer m.

Return the maximum product of the first and last elements of any subsequence of nums of size m.

Example 1:

Input: nums = [-1,-9,2,3,-2,-3,1], m = 1

Output: 81

Explanation:

The subsequence [-9] has the largest product of the first and last elements: -9 * -9 = 81. Therefore, the answer is 81.

Example 2:

Input: nums = [1,3,-5,5,6,-4], m = 3

Output: 20

Explanation:

The subsequence [-5, 6, -4] has the largest product of the first and last elements.

Example 3:

Input: nums = [2,-1,2,-6,5,2,-5,7], m = 2

Output: 35

Explanation:

The subsequence [5, 7] has the largest product of the first and last elements.

Constraints:

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105
  • 1 <= m <= nums.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the definition of a subsequence in this context? Does the relative order of elements from the original array need to be preserved?
  2. What are the constraints on the length of the subsequence $k$ relative to the size of the array, and what should be returned if $k$ is greater than the length of the array?
  3. Can the array contain negative numbers and zeros, and how should combinations of negative and positive endpoints affect the product calculation?
  4. If multiple subsequences yield the same maximum product, do we need to return any specific subsequence or just the numerical product value?
  5. What are the bounds on the size of the array and the values of the elements (e.g., could they exceed standard 32-bit integer limits when multiplied)?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we want to look at every single possible way to pick items from the given sequence while keeping their original order. For each valid group of items we can form, we multiply the very first item by the very last item, and then we simply find the largest result among all the groups we checked.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the entire sequence of items from start to finish.
  2. Generate every possible smaller collection of items that you can form by picking some items while keeping them in their original order.
  3. For each of these collections, identify the first item and the last item.
  4. Multiply those two specific items together to get a product score for that collection.
  5. Write down or remember this score.
  6. Repeat this multiplication process for every other possible collection you generated.
  7. Compare all the recorded scores and select the biggest one as your final answer.

Code Implementation

def maximum_product_first_last_subsequence(sequence):    # Handle edge cases where a valid subsequence of at least length one cannot be formed    if not sequence:        return 0    maximum_product_found = float('-inf')    # Enumerate all possible subsets to evaluate every valid order-preserving subsequence    total_subsets = 1 << len(sequence)    for subset_index in range(total_subsets):        current_subsequence = []        for element_index in range(len(sequence)):            if (subset_index & (1 << element_index)) > 0:                current_subsequence.append(sequence[element_index])        # Only evaluate non-empty subsequences where first and last boundaries exist        if len(current_subsequence) > 0:            first_element = current_subsequence[0]            last_element = current_subsequence[-1]            current_product = first_element * last_element            if current_product > maximum_product_found:                maximum_product_found = current_product    # Return the highest product computed across all generated subsequences    return maximum_product_found

Big(O) Analysis

Time Complexity
O(2ⁿ) – To generate every possible subsequence from a sequence of size n, we make a binary choice for each element to either include it or exclude it. Since there are n elements and 2 choices for each, this process generates a total of 2ⁿ distinct subsequences. For each of these subsequences, we identify the first and last elements and multiply them in constant time. Summing the work across all generated subsequences results in approximately 1 * 2ⁿ operations, which simplifies to O(2ⁿ).
Space Complexity
O(2^N) – The brute force approach requires generating every possible subsequence from the input sequence of size N. Since a sequence of length N has 2^N possible subsequences, generating and storing or recursively evaluating each collection requires keeping track of states that grow exponentially. The recursion stack depth or the storage required to hold these combinations scales proportionally with the number of generated subsets, leading to exponential auxiliary space.

Optimal Solution

Approach

Instead of testing every possible combination of numbers, the optimal approach relies on a clever observation about how multiplication works with positive and negative values. By keeping track of the absolute biggest and smallest numbers seen so far, we can instantly figure out the best possible outcome without doing unnecessary work.

Here's how the algorithm would work step-by-step:

  1. Scan through the collection of numbers from the beginning to the end, one by one.
  2. Keep a mental note of the largest number and the smallest number encountered as the scan progresses.
  3. Whenever a new number is considered, imagine it as the potential ending point of a sequence.
  4. To get the biggest possible product for this ending point, multiply it by the largest number seen so far, or by the smallest number seen so far in case two negative numbers turn into a huge positive.
  5. Compare this result against the best overall product found so far and update the record if a new high score is reached.
  6. Continue this process for every number in the collection until the end is reached.
  7. By the end of the scan, the highest recorded product will be your final answer, having checked every winning possibility in just a single pass.

Code Implementation

def max_product_endpoints(sequence_of_numbers):
    if not sequence_of_numbers:
        return 0

    maximum_so_far = sequence_of_numbers[0]
    minimum_so_far = sequence_of_numbers[0]
    max_product_result = float('-inf')

    # Evaluate each number as a potential ending point to check all subsequences in one pass.
    for current_number in sequence_of_numbers:

        # Multiplying extreme values handles both positive growth and negative number reversals.
        candidate_product_one = current_number * maximum_so_far
        candidate_product_two = current_number * minimum_so_far
        max_product_result = max(max_product_result, candidate_product_one, candidate_product_two)

        # Track extreme values to ensure future products capture the widest possible range.
        maximum_so_far = max(maximum_so_far, current_number)
        minimum_so_far = min(minimum_so_far, current_number)

    return max_product_result

Big(O) Analysis

Time Complexity
O(n) – The algorithm scans through the collection of n numbers exactly once from beginning to end in a single pass. During this scan, constant-time operations are performed to update the minimum, maximum, and potential products for each element. Since there are no nested loops, recursion, or repeated scans, the total number of operations scales linearly with the input size. Therefore, the time complexity simplifies to O(n).
Space Complexity
O(1) – The algorithm only maintains a few primitive variables to track the maximum number, minimum number, and best overall product as it scans through the input. Because it processes each number on the fly without storing any intermediate sequences, no extra data structures scale with the input size N. Therefore, the auxiliary space remains constant regardless of how many elements are in the collection.

Edge Cases

Subsequence length k is greater than the array length
How to Handle:
Return an error or a default value since no such subsequence can be formed.
Subsequence length k equals 1
How to Handle:
The first and last elements are the same, so compute the square of each element and return the maximum value.
Array contains a mix of large positive and negative numbers causing integer overflow
How to Handle:
Use 64-bit integer types for all product calculations to prevent arithmetic overflow.
Array contains only negative numbers with various magnitudes
How to Handle:
Track both the minimum and maximum values seen so far to correctly compute products of negative extremes.
Array contains multiple zeros and extreme boundary values
How to Handle:
Ensure zero products are handled correctly alongside very large positive and negative products.
Subsequence length k equals the array length
How to Handle:
Only a single subsequence exists, so directly multiply the first and last elements of the entire array.
Extremely large array size causing performance bottlenecks
How to Handle:
Design a linear or logarithmic time complexity algorithm instead of generating all combinations to avoid time limit exceedance.
0/11 completed