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)
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)
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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools