博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode152——Maximum Product Subarray
阅读量:3977 次
发布时间:2019-05-24

本文共 1873 字,大约阅读时间需要 6 分钟。

文章作者:Tyan

博客:  |   | 

1. 问题描述

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],

the contiguous subarray [2,3] has the largest product = 6.

2. 求解

这个题跟Leetcode 53——Maximum Subarray类似,可以用三重循环,两种循环解决。但最好的还是用动态规划解决,找出状态转移方程最关键。由于乘积可能为负数,负负得正,因此第i-1次的乘积最大值(maxValuePre)与最小值(minValuePre)都需要保留。当然也可以定义最大值最小值数组来保存第i次乘积的最大值(maxValue)与最小值(minValue)。与Maximum Subarray相比,最大值为maxValue = max(minValuePre * nums[i], maxValuePre * nums[i], nums[i]),最小值同样如此。

没有定义最大值数组与最小值数组

public class Solution {    public int maxProduct(int[] nums) {        int n = nums.length;        int maxValue = nums[0];        int minValue = nums[0];        int result = nums[0];        int maxValuePre = nums[0], minValuePre = nums[0];        for(int i = 1; i < n; i++) {            maxValue = Math.max(minValuePre * nums[i], Math.max(maxValuePre * nums[i], nums[i]));            minValue = Math.min(minValuePre * nums[i], Math.min(maxValuePre * nums[i], nums[i]));            if(maxValue > result) {                result = maxValue;            }            maxValuePre = maxValue;            minValuePre = minValue;        }        return result;    }}

定义最大值数组与最小值数组

public class Solution {    public int maxProduct(int[] nums) {        int n = nums.length;        int maxValue[] = new int[nums.length];        int minValue[] = new int[nums.length];        maxValue[0] = nums[0];        minValue[0] = nums[0];        int result = nums[0];        for(int i = 1; i < n; i++) {            maxValue[i] = Math.max(minValue[i - 1] * nums[i], Math.max(maxValue[i - 1] * nums[i], nums[i]));            minValue[i] = Math.min(minValue[i - 1] * nums[i], Math.min(maxValue[i - 1] * nums[i], nums[i]));            if(maxValue[i] > result) {                result = maxValue[i];            }        }        return result;    }}

转载地址:http://sdwui.baihongyu.com/

你可能感兴趣的文章
常用STL算法2_查找
查看>>
常用STL算法3_排序
查看>>
常用STL算法4_拷贝和替换
查看>>
STL综合案例
查看>>
O(logn)时间复杂度求Fibonacci数列
查看>>
Iterator_traits
查看>>
Zedboard中的SPI通信记录文档(已实现)
查看>>
Android 发布到google Play的app搜索不到问题的解决
查看>>
Flutter 网络请求之基于dio的简单封装
查看>>
Flutter UI基础 - 路由之Navigator详解
查看>>
Flutter UI基础 - Widgets 之 InkWell 和 Ink
查看>>
Spring - sentinel和hystrix比较
查看>>
Flutter 日期插件date_format 中文 国际化 及flutter_cupertino_date_picker
查看>>
Flutter 插件笔记 | 屏幕适配 flutter_screenutil
查看>>
Flutter UI基础 - 侧拉抽屉菜单
查看>>
Flutter UI基础 - AppBar中标题文字如何居中
查看>>
Flutter UI基础 - Drawer 抽屉视图与自定义header
查看>>
Flutter UI基础 - GridView
查看>>
Flutter UI基础 - 使用InkWell给任意Widget添加点击事件
查看>>
OC WKWebView的使用
查看>>