LeetCode dynamic programming product maximum subarray

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

topic

Subarray with the largest product
You are given an integer array nums , please find the non-empty continuous subarray with the largest product in the array (the subarray contains at least one number), and return the product corresponding to the subarray.
The answer to the test case is a 32-bit integer.
子数组is a contiguous subsequence of an array.

Example 1:

输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
复制代码

Example 2:

输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
复制代码

hint:

1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums 的任何前缀或后缀的乘积都 保证 是一个 32-位 整数
复制代码

answer

problem-solving analysis

Problem solving ideas

  1. This problem is a typical dynamic programming problem;
  2. We need to keep traversing the array to get the maximum value maxF = Math.max(mx * nums[i], nums[i]);;
  3. Due to the existence of negative numbers in the array, it may cause the largest value to become the smallest value and the smallest value to become the largest value. Therefore, it is also necessary to maintain the current minimum value

minF = Math.min(mn * nums[i], nums[i]); 4. If a negative number occurs, min, max are exchanged and then the next calculation is performed;

Complexity Analysis

  • Time complexity: O(N)
  • Space Complexity: O(1)

problem solving code

The solution code is as follows (detailed comments in the code):

class Solution {
    public int maxProduct(int[] nums) {
        // maxF 最大值, minF 最小值, ans 结果
        int maxF = nums[0], minF = nums[0], ans = nums[0];
        // 数组长度
        int len = nums.length;
        for (int i =1; i < len; i++) {
            // 保存旧数据
            int mx = maxF , mn = minF;
            // 更新最大值
            maxF = Math.max(mx * nums[i], Math.max(nums[i], mn * nums[i]));
            // 更新最小值
            minF = Math.min(mn * nums[i], Math.min(nums[i], mx * nums[i]));
            // 更新结果
            ans = Math.max(maxF, ans);
        }
        // 返回
        return ans;
    }
}
复制代码

Feedback results after submission:

image.png

Reference Information

Guess you like

Origin juejin.im/post/7079266074734100511