search
HomeWeb Front-endJS TutorialLeetCode Meditations: Maximum Product Subarray

LeetCode Meditations: Maximum Product Subarray

The description for Maximum Product Subarray is:

Given an integer array nums, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

For example:

Input: nums = [2, 3, -2, 4]
Output: 6
Explanation: [2, 3] has the largest product 6.
Input: nums = [-2, 0, -1]
Output: 0
Explanation: The result cannot be 2, because [-2, -1] is not a subarray.

Now, using a brute force approach, we can solve it with a nested loop.

Since we eventually have to get the maximum product, let's first find out the maximum value in the array:

let max = Math.max(...nums);

Then, as we go through each number, we can continually multiply them with the other remaining numbers, building up a total. Once this total is more than max, we can update max to point to this new value:

for (let i = 0; i  max) {
      max = total;
    }
  }
}

At the end, we can just return max. So, the first attempt of our final solution looks like this:

function maxProduct(nums: number[]): number {
  let max = Math.max(...nums);
  for (let i = 0; i  max) {
        max = total;
      }
    }
  }

  return max;
}

Time and space complexity

The time complexity is O(n2)O(n^2) O(n2) as we have a nested loop, doing a constant operation for each of the numbers for each one we iterate over.
The space complexity is O(1)O(1) O(1) because we don't need additional storage.

Again, this is only a brute force attempt. So, let's take one deep breath, and take a look at another solution.


The idea with this new solution is to keep two different values for the maximum and minimum as we go through each number in the array. The reason for that is handling negative values, as we'll see shortly.

First, let's start with initializing these values: we'll have a currentMax, a currentMin, and a result, all of which are initially pointing to the first value in the array:

let currentMax = nums[0];
let currentMin = nums[0];
let result = nums[0];

Now, starting with the second number, we'll loop through each value, updating the current maximum number and the current minimum number as well as the result (which will be the final maximum) as we go:

for (let i = 1; i 



<p>However, before that, let's see an example of what can happen if we just do that.</p>

<p>Let's say our array is [-2, 3, -4]. Initially, currentMax and currentMin are both -2. Now, to update currentMax, we have two options: it's either the current number or the current number multiplied by currentMax:<br>
</p>

<pre class="brush:php;toolbar:false">Math.max(3, 3 * -2)

Obviously, it's the first option, so our currentMax is now 3.
To update currentMin, we also have two options:

Math.min(3, 3 * -2)

It's again obvious, -6. For now, our values look like this:

currentMax // 3
currentMin // -6

On to the next number. We have two options for currentMax:

Math.max(-4, -4 * 3)

By itself, it has to be -4, but looking at our array, we see that this is not the case. Since multiplying two negative values results in a positive value, our currentMax should be 24 (-2 * 3 * -4).

Note
If we were to multiply it with currentMin, we reach this value: -4 * -6 = 24.

Also, let's look at our currentMin options:

Math.min(-4, -4 * -6)

This has to be -4 again, but something feels off.

The catch is that when we have negative numbers consecutively, our sign alternates, which affects the maximum result we need. That's why we're keeping track of the minimum value in the first case: to keep track of the sign.

Since the issue is just alternating signs, we can simply swap the maximum and minimum values when we're looking at a negative number before updating those values:

if (nums[i] 



<p>Also, note that we're taking the product of each previous subarray as we go, essentially solving a smaller portion of the problem.</p>

<p>And that's it, our final solution looks like this:<br>
</p>

<pre class="brush:php;toolbar:false">function maxProduct(nums: number[]): number {
  let currentMax = nums[0];
  let currentMin = nums[0];
  let result = nums[0];

  for (let i = 1; i 



<h4>
  
  
  Time and space complexity
</h4>

<p>The time complexity for this solution is 

  <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>O</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo></mrow>O(n) </semantics></math><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;">O(n)</span></span></span>
</span>
 because we go through each number once doing a constant operation. </p>

<div class="table-wrapper-paragraph"><table>
<thead>
<tr>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Math.max() and Math.min() are constant operations here, since we're comparing two values only. However, if we were to find max or min of a whole array, it would be 

  <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>O</mi><mo stretchy="false">(</mo><mi>n</mi><mo stretchy="false">)</mo></mrow>O(n) </semantics></math><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;">O(n)</span></span></span>
</span>
 as the time complexity of the operation would increase proportionately to the size of the array.</td>
</tr>
</tbody>
</table></div>

<p>The space complexity is 

  <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>O</mi><mo stretchy="false">(</mo><mn>1</mn><mo stretchy="false">)</mo></mrow>O(1) </semantics></math><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;">O(1)</span></span></span>
</span>
 since we don't need any additional storage.</p>


<hr>

<p>The next problem on the list is called Word Break. Until then, happy coding.</p>


          

            
  

            
        

The above is the detailed content of LeetCode Meditations: Maximum Product Subarray. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools