Maximum Product of First and Last Elements of a Subsequence Problem
#3584
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3584.
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 <= 10^5-10^5 <= nums[i] <= 10^51 <= m <= nums.length
Solution
Approach: Fix the Last Element, Track Prefix Extremes
Take nums[i] as the last element of a subsequence of length m. The first element can be any nums[j] with j <= i - m + 1, since m - 2 elements still fit in between. The best product with nums[i] is therefore nums[i] times either the smallest or the largest such nums[j] (the sign of nums[i] decides which).
Sweep i from m - 1 to the end, adding nums[i - m + 1] to the running minimum mi and maximum mx each step, and keep the largest of nums[i] * mi and nums[i] * mx.
Complexity: O(n) time and O(1) space.
from math import inf
class Solution:
def maximumProduct(self, nums: List[int], m: int) -> int:
ans = mx = -inf
mi = inf
for i in range(m - 1, len(nums)):
x = nums[i]
y = nums[i - m + 1]
mi = min(mi, y)
mx = max(mx, y)
ans = max(ans, x * mi, x * mx)
return ans