1- #Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
2- #It is guaranteed that the answer will fit in a 32-bit integer.
3- #A subarray is a contiguous subsequence of the array.
4-
5- #Example 1:
6- #Input: nums = [2,3,-2,4]
7- #Output: 6
8- #Explanation: [2,3] has the largest product 6.
9-
10- #Example 2:
11- #Input: nums = [-2,0,-1]
12- #Output: 0
13- #Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
14-
15- #Constraints:
16- #1 <= nums.length <= 2 * 104
17- #-10 <= nums[i] <= 10
18- #The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
191
2+ # Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
3+ # It is guaranteed that the answer will fit in a 32-bit integer.
4+ # A subarray is a contiguous subsequence of the array.
205
6+ # Example 1:
7+ # Input: nums = [2,3,-2,4]
8+ # Output: 6
9+ # Explanation: [2,3] has the largest product 6.
2110
11+ # Example 2:
12+ # Input: nums = [-2,0,-1]
13+ # Output: 0
14+ # Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
2215
23- #Dynamic Programming Approach (Kadane's Algorithm) - O(n) Time / O(1) Space
24- #Track both current minimum and current maximum (Due to possibility of multiple negative numbers)
25- #Answer is the highest value of current maximum
16+ # Constraints:
17+ # 1 <= nums.length <= 2 * 104
18+ #-10 <= nums[i] <= 10
19+ # The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
2620
21+ # Dynamic Programming Approach (Kadane's Algorithm) - O(n) Time / O(1) Space
22+ # Track both current minimum and current maximum (Due to possibility of multiple negative numbers)
23+ # Answer is the highest value of current maximum
2724
2825# @param {Integer[]} nums
2926# @return {Integer}
3027def max_product ( nums )
31- return nums [ 0 ] if nums . length == 1
32-
33- cur_min , cur_max , max = 1 , 1 , -11
34-
35- nums . each do |val |
36- tmp_cur_max = cur_max
37- cur_max = [ val , val *cur_max , val *cur_min ] . max
38- cur_min = [ val , val *tmp_cur_max , val *cur_min ] . min
39-
40- max = [ max , cur_max ] . max
41- end
42-
43- max
44- end
28+ return nums [ 0 ] if nums . length == 1
29+
30+ cur_min = 1
31+ cur_max = 1
32+ max = -11
33+
34+ nums . each do |val |
35+ tmp_cur_max = cur_max
36+ cur_max = [ val , val * cur_max , val * cur_min ] . max
37+ cur_min = [ val , val * tmp_cur_max , val * cur_min ] . min
38+
39+ max = [ max , cur_max ] . max
40+ end
41+
42+ max
43+ end
44+
45+ nums = [ 2 , 3 , -2 , 4 ]
46+ puts max_product ( nums )
47+ # Output: 6
48+
49+ nums = [ -2 , 0 , -1 ]
50+ puts max_product ( nums )
51+ # Output: 0
0 commit comments