-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path152.maximum-product-subarray.java
More file actions
88 lines (77 loc) · 1.99 KB
/
Copy path152.maximum-product-subarray.java
File metadata and controls
88 lines (77 loc) · 1.99 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* @lc app=leetcode id=152 lang=java
*
* [152] Maximum Product Subarray
*
* https://leetcode.com/problems/maximum-product-subarray/description/
*
* algorithms
* Medium (29.34%)
* Total Accepted: 215.1K
* Total Submissions: 731.9K
* Testcase Example: '[2,3,-2,4]'
*
* Given an integer array nums, find the contiguous subarray within an array
* (containing at least one number) which has the largest product.
*
* Example 1:
*
*
* Input: [2,3,-2,4]
* Output: 6
* Explanation: [2,3] has the largest product 6.
*
*
* Example 2:
*
*
* Input: [-2,0,-1]
* Output: 0
* Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
*
*/
class Solution {
/** Timeout
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int n = nums.length;
int[][] dp = new int[n][n];
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (nums[j] == 0) {
break;
}
if (i == j) {
dp[i][j] = nums[i];
} else {
dp[i][j] = dp[i][j - 1] * nums[j];
}
max = Math.max(dp[i][j], max);
}
}
return max;
} */
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int res = nums[0];
int max = nums[0];
int min = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] >= 0) {
max = max > 0 ? max * nums[i] : nums[i];
min = min <= 0 ? min * nums[i] : nums[i];
} else {
int tmp = max;
max = min <= 0 ? min * nums[i] : nums[i];
min = tmp > 0 ? tmp * nums[i] : nums[i];
}
res = Math.max(res, max);
}
return res;
}
}