Skip to content

Commit 41ceee2

Browse files
committed
Update maxProductSubarray and minRotatedSortedarray algorithms
1 parent fdd362b commit 41ceee2

File tree

4 files changed

+80
-52
lines changed

4 files changed

+80
-52
lines changed
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
function maxProductSubArray(nums) {
2-
let result = nums[0];
3-
let currentMax = currentMin = 1;
2+
let result = nums[0], currentMax = nums[0], currentMin = nums[0];
43

5-
for(let num of nums) {
6-
let tempMaxProduct = currentMax * num;
7-
let tempMinProduct = currentMin * num;
8-
currentMax = Math.max(Math.max(tempMaxProduct, tempMinProduct), num);
9-
currentMin = Math.min(Math.min(tempMaxProduct, tempMinProduct), num);
4+
for(let i=1; i < nums.length; i++) {
5+
const num = nums[i];
6+
const tempMaxProduct = currentMax * num;
7+
const tempMinProduct = currentMin * num;
8+
currentMax = Math.max(num, tempMaxProduct, tempMinProduct);
9+
currentMin = Math.min(num, tempMaxProduct, tempMinProduct);
1010
result = Math.max(result, currentMax);
1111
}
1212
return result;
1313
}
1414

1515
let numbers1 = [6, 7,-4, 5, 8, 1];
1616
console.log(maxProductSubArray(numbers1));
17-
let numbers2 = [2, 7,-4, 0, 3, 3];
17+
let numbers2 = [2, -7, -4, 0, 3, 3];
1818
console.log(maxProductSubArray(numbers2));

src/javascript/algorithms/array/8.maxProductSubarray/maxProductSubarray.md

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,35 +7,51 @@ Input: nums = [6, 7,-4, 5, 8, ]
77
Output: 6
88

99
Example 2:
10-
Input: nums = [-2,0,-2]
10+
Input: nums = [-2, 0, -2]
1111
Output: 0
1212

13-
**Algorithmic Steps:**
13+
## Algorithmic Steps
1414

15-
This problem is solved with the help of **Kadane's algorithm**(dynamic programming technique). The algorithmic approach can be summarized as follows:
15+
This problem is efficiently solved using a variation of **Kadane's Algorithm** tailored for products. It tracks both the **maximum** and **minimum** product ending at each position, due to the behavior of negative numbers.
1616

17-
1. Initialize the maximum product subarray(`result`) with a first number.
17+
1. **Initialize** three variables with the first element of the array `nums[0]`:
18+
- `result`: Holds the maximum product found so far.
19+
- `currentMax`: Tracks the maximum product ending at the current index.
20+
- `currentMin`: Tracks the minimum product ending at the current index.
1821

19-
**Note:** It is not suggested to assign the value to either 0 or 1 because the maximum value can be less than or equal to 0.
22+
> **Note:** We initialize all three with the first element instead of 1 or 0 to properly account for arrays with negative or single values.
2023
21-
2. Initialize two variables named `currentMax` and `currentMin` to `1`. They are used to keep track of the running maximum and minimum products.
24+
2. **Iterate** over the array starting from the second element to last element:
2225

23-
3. Iterate over the entire input array using for-of loop
26+
3. For each element `num`:
27+
- Compute temporary products using the previous `currentMax` and `currentMin`:
28+
- `tempMax = currentMax * num`
29+
- `tempMin = currentMin * num`
2430

25-
4. Find the temporary maximum and minimum products for each current element.
31+
4. **Update** `currentMax` by taking the maximum among:
32+
- `num` (start new subarray)
33+
- `tempMax`
34+
- `tempMin`
35+
This ensures that the current maximum product is correctly tracked.
2636

27-
5. Calculate the maximum value between maximum and minimum values of step4, and this calculated maximum result needs to be compared with current element to find the final current maximum product.
37+
5. **Update** `currentMin` by taking the minimum among:
38+
- `num`
39+
- `tempMax`
40+
- `tempMin`
41+
This is crucial for handling negative values, which could turn a future product into a maximum.
2842

29-
**Note:** Since an array contain both positive and negative integers, the product of current element with minimum product calculated so far may result into maximum value. That is the reason why we took maximum of current maximum and current minimum proucts.
43+
6. **Update** the global `result` by taking the maximum of:
44+
- `result`
45+
- `currentMax`
46+
This ensures the highest product is captured across the entire array.
3047

31-
6. Calculate the minimum value between maximum and minimum values of step4, and this calculated minimum result needs to be compared with current element to find the final current minimum product. This current minimum product is useful to calculate the maximum value for the next iteration.
48+
7. After the loop completes, **return** the `result`, which contains the maximum product of any contiguous subarray.
3249

33-
7. Update the global maximum product by taking the maximum of current maximum product and global maximum product of previous iteration.
50+
---
3451

35-
8. Return the global maximum `result` after the end of for-each iteration.
52+
## Time and Space Complexity
3653

37-
**Time and Space complexity:**
54+
- **Time Complexity**: `O(n)` — We traverse the input array once.
55+
- **Space Complexity**: `O(1)` — No extra space is used except for a few variables.
3856

39-
This algorithm has a time complexity of `O(n)`, where `n` is the number of elements. This is because we iterate the array at most once.
40-
41-
Here, we don't use any additional datastructure other than the two sum variables. Hence, the space complexity will be O(1).
57+
---
Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,32 @@
1-
function minRotatedSortedArray(nums) {
2-
let result = nums[0];
1+
function minRotatedSortedarray(nums) {
32
if(nums.length === 1) return nums[0];
43
if(nums.length === 2) return Math.min(nums[0], nums[1]);
54

6-
let left = 0, right = nums.length - 1;
5+
let left = 0;
6+
let right = nums.length - 1;
77

8-
while(left < right) {
9-
if(nums[left] < nums[right]) {
10-
result = nums[left];
11-
break;
12-
}
8+
while (left < right) {
9+
// If the array is already sorted
10+
if (nums[left] < nums[right]) return nums[left];
1311

14-
let mid = left + (right - left)/2;
12+
const mid = Math.floor((left + right) / 2);
1513

16-
if(nums[mid] > nums[right]) {
14+
if (nums[mid] > nums[right]) {
15+
// Minimum is in the right half
1716
left = mid + 1;
1817
} else {
18+
// Minimum is in the left half (including mid)
1919
right = mid;
2020
}
2121
}
22-
return result;
22+
23+
return nums[left]; // or arr[right], both are the same here
2324
}
2425

26+
27+
2528
let sortedArray = [3, 4, 5, 6, 7, 1, 2];
26-
console.log(minRotatedSortedArray(sortedArray));
29+
console.log(minRotatedSortedarray(sortedArray));
2730

2831
let sortedArray1 = [0, 1, 2, 4, 5, 6, 7, 8];
29-
console.log(minRotatedSortedArray(sortedArray1));
32+
console.log(minRotatedSortedarray(sortedArray1));

src/javascript/algorithms/array/9.minRotatedSortedarray/minRotatedSortedarray.md

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
**Description:**
22
Given a sorted array `nums` of length `n` with all unique elements, in which the array is rotated between 1 and n times. Return the minimum element of this array.
33

4-
**Note:** You need to write an algorithm that runs in O(log n) time.
4+
**Note:** You need to write an algorithm that runs in `O(log n)` time.
55

66
### Examples
77
Example 1:
@@ -14,27 +14,36 @@ Output: 0
1414

1515
**Algorithmic Steps:**
1616

17-
This problem is solved with the help of **binary search** technique. Since it is a rotated sorted array, there will be two subararys of elements in an ascending order. Once you find the correct subarray, the left most element is the minimum value. The algorithmic approach can be summarized as follows:
17+
This problem can be efficiently solved using the **binary search** technique. Because the array is a rotated version of a sorted array, it consists of two ascending subarrays. By identifying which subarray contains the minimum element, we can narrow down the search. The minimum value will always be the leftmost element of the correctly identified subarray. The algorithmic approach can be summarized as follows:
1818

19-
1. Initialize the minimum value(`result`) to first element of an array.
2019

21-
2. Add preliminary checks by returning the first element if the length of array is one, or minimum of first two values if the length of an array is two.
20+
1. **Initialize the Result:**
21+
- Set the initial minimum value `result` to the first element of the array.
2222

23-
3. Initialize left and right pointers(`left` and `right`) to first index and last index of an array.
23+
2. **Handle Base Cases:**
24+
- If the array length is `1`, return the only element.
25+
- If the array length is `2`, return the smaller of the two elements.
2426

25-
4. Iterate over an input array using while loop with the condition of left pointer is less than or equal to right pointer.
27+
3. **Set Search Boundaries:**
28+
- Initialize two pointers: `left` at the start (index 0), and `right` at the end (index `n - 1`) of the array.
2629

27-
5. If the left element is less than or equal to right element, update the result value and break the while loop to return the minimum value.
30+
4. **Iterate Using Binary Search:**
31+
- While `left < right`:
32+
- Check if the subarray between `left` and `right` is already sorted:
33+
- If `nums[left] < nums[right]`, return `nums[left]` as the minimum.
34+
- Compute the middle index: `mid = Math.floor((left + right) / 2)`.
2835

29-
6. Calculate the middle index of an array to separate the sorted subarrays.
36+
5. **Decide Which Half to Search:**
37+
- If `nums[mid] > nums[right]`:
38+
- The minimum lies in the **right half**.
39+
- Move `left` pointer to `mid + 1`.
40+
- Otherwise:
41+
- The minimum lies in the **left half** (including `mid`).
42+
- Move `right` pointer to `mid`.
3043

31-
7. If the middle value is greater than right most element, the minimum value exists with in the right side subarray. So the left pointer will be updated to next element of middle element.
44+
6. **Return Minimum:**
45+
- After the loop ends, `nums[left]` holds the minimum element in the rotated sorted array.
3246

33-
8. If the middle value is less than or equal to left most element, the minimum value exists with in the left side subarray. So the right pointer will be updated to the middle element.
34-
35-
9. Repeat steps 4-7 until you find the left most value which is minimum in the entire input array.
36-
37-
10. Return the result element after the end of an iteration.
3847

3948
**Time and Space complexity:**
4049

0 commit comments

Comments
 (0)