-
Notifications
You must be signed in to change notification settings - Fork 3
/
_0152_MaximumProductSubarray.java
71 lines (67 loc) · 2.54 KB
/
_0152_MaximumProductSubarray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.diguage.algorithm.leetcode;
/**
* = 152. Maximum Product Subarray
*
* https://leetcode.com/problems/maximum-product-subarray/[Maximum Product Subarray - LeetCode]
*
* Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
*
* .Example 1:
* [source]
* ----
* Input: [2,3,-2,4]
* Output: 6
* Explanation: [2,3] has the largest product 6.
* ----
*
* .Example 2:
* [source]
* ----
* Input: [-2,0,-1]
* Output: 0
* Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
* ----
*
* @author D瓜哥, https://www.diguage.com/
* @since 2020-01-05 07:59
*/
public class _0152_MaximumProductSubarray {
/**
* Runtime: 1 ms, faster than 97.91% of Java online submissions for Maximum Product Subarray.
*
* Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Maximum Product Subarray.
*
* Copy form: https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity[Possibly simplest solution with O(n) time complexity - LeetCode Discuss]
*/
public int maxProduct(int[] nums) {
// store the result that is the max we have found so far
int result = nums[0];
// max/min stores the max/min product of
// subarray that ends with the current number nums[i]
for (int i = 1, max = result, min = result; i < nums.length; i++) {
// multiplied by a negative makes big number smaller, small number bigger
// so we redefine the extremums by swapping them
if (nums[i] < 0) {
int temp = max;
max = min;
min = temp;
}
// max/min product for the current number is either the current number itself
// or the max/min by the previous number times the current one
min = Math.min(nums[i], min * nums[i]);
max = Math.max(nums[i], max * nums[i]);
// the newly computed max value is a candidate for our global result
result = Math.max(result, max);
}
return result;
}
public static void main(String[] args) {
_0152_MaximumProductSubarray solution = new _0152_MaximumProductSubarray();
int[] n1 = {2, 3, -2, 4};
int r1 = solution.maxProduct(n1);
System.out.println((r1 == 6) + " : " + r1);
int[] n2 = {-2, 0, -1};
int r2 = solution.maxProduct(n2);
System.out.println((r2 == 0) + " : " + r1);
}
}