#3584

Maximum Product of First and Last Elements of a Subsequence

Medium
ArrayTwo PointersTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all subsequences, we can find the maximum product by iterating through the array and maintaining the maximum and minimum values dynamically.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize maxProduct to a very small value.
  2. 2Step 2: Iterate through the array, considering each element as a potential first element of a subsequence.
  3. 3Step 3: For each valid first element, calculate the product with the maximum last element from the remaining elements.
solution.py7 lines
1def maxProduct(nums, m):
2    maxProduct = float('-inf')
3    n = len(nums)
4    for i in range(n - m + 1):
5        maxLast = max(nums[i + m - 1:])
6        maxProduct = max(maxProduct, nums[i] * maxLast)
7    return maxProduct

Complexity note: This approach runs in linear time by iterating through the array and calculating products dynamically.

  • 1Maximize the first element and find the best possible last element.
  • 2Consider both negative and positive values for maximum product.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.