product maximum subarray
Question description: Given an integer array
nums
, please find the contiguous subarray with the largest product in the array (the subarray contains at least one number), and return the corresponding product of the subarray.For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/maximum-product-subarray/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Exhaustive method
First, if the array nums has only one element, return that number directly.
Otherwise, by enumerating the product of all possible contiguous subarrays, and then obtaining the larger one, use result to record the maximum value, and initialize it to the value of the first element of the array nums, as follows:
- Traverse from the first element as the first element of a continuous subarray;
- Then the inner loop is the last array as the contiguous subarray. In the process, it is necessary to judge whether the product of the current contiguous subarray is greater than the result, and if so, update the value of the result.
Finally, the return result is the largest product.
public class LeetCode_152 {
/**
* 穷举法
*
* @param nums 原数组
* @return 返回数组中乘积最大的连续子数组的乘积
*/
public static int maxProduct(int[] nums) {
// 如果数组nums只有一个元素,直接返回这个数
if (nums.length == 1) {
return nums[0];
}
// result记录当期的最大值
int result = nums[0];
// 从数组的nums的第一个元素开始遍历
for (int i = 0; i < nums.length; i++) {
int cur = nums[i];
// result取较大值
result = Math.max(result, cur);
// 当前元素直到和最后一个元素的累乘
for (int j = i + 1; j < nums.length; j++) {
cur = cur * nums[j];
// result取最大值
result = Math.max(result, cur);
}
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{2, 3, -2, 4};
// 测试用例,期望输出: 6
System.out.println(maxProduct(nums));
}
}
[Daily Message] Dissatisfaction is an upward wheel, which can carry dissatisfied people forward.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。