BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features49 of 54 in topic

837. Find the largest product of a contiguous run

MediumData processing and features Pro

You log a multiplicative change factor for every training step, as whole numbers that can be positive, zero or negative. You want the contiguous run of steps whose factors multiply to the largest value.

Write max_product_run(nums) that returns the largest product of any non-empty contiguous slice of nums.

Functiondef max_product_run(nums)

Example 1

Input: max_product_run([2, 3, -2, 4])

Output: 6, from the slice [2, 3]

Example 2

Input: max_product_run([-2, 3, -4])

Output: 24

Explanation: Because two negatives multiply to a positive.

Constraints

  • 1 <= len(nums) <= 20,000
  • Each value is an integer between -10 and 10.
Hint 1

Keep the max and the min product ending at the current index.

Hint 2

Negative x swaps the roles of max and min.

Hint 3

Start every state from nums[0], not from 1 or 0.

Common mistakes
  • Starting best at 0, which is wrong for [-5].
  • Updating cur_max first and then using the new value to compute cur_min.
  • Forgetting that x alone can beat any extended slice after a zero.
Understand the idea

This is Kadane style dynamic programming with two states instead of one. For sums, the best slice ending at i only needs the best slice ending at i - 1. For products, sign flips mean you also need the worst (most negative) slice ending at i - 1, since multiplying it by a negative number can make it the best. With [-2, 3, -4]: after -2 the pair is (max -2, min -2); after 3 it is (3, -6); after -4 it becomes (24, -12), giving 24.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
837 / 903
Python 3solution.pyPython idle
1
2
3
4
def max_product_run(nums):
# return the largest product of a contiguous non-empty slice
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS