[LeetCode]152. Maximum Product Subarray
2016-02-04 18:52
435 查看
Problem Description
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.
Subscribe to see which companies asked this question
[]https://leetcode.com/problems/maximum-product-subarray/]
思路
使用DP!使用DP!没有看标签之前思路错了,导致浪费了一下午的时间找边界值(还是没有事先写好Testcase的锅)。错误思路是使用0将数组区间分成若干部分,每个小部分进行负数的计数,并保存第一个和最后一个负数的位置,这样就可以计算出若干部分每个的MAX Product,再从中求最大值即可。但是!但是!但是!!这明明是一道DP的问题啊啊啊啊!!!(还是做题不多的锅)。。
DP的思路就很简单惹。。。O(n)的遍历数组,保存一个最大值和一个最小值(绝对值最大的负数),每次循环都会检查是否会产生一个新的最大值。
一开始没敢往DP方向想是考虑到没有重复值问题,比如a,b,c,d。如果a*b**c
Code
package Q152; import java.lang.Math; public class Solution { public static int maxProduct(int[] nums) { if(nums.length==1) return nums[0]; int max=0; int min=0; int tmp; int ans=0; for(int i=0;i<nums.length;i++){ tmp=max; max=Math.max(Math.max(tmp*nums[i], min*nums[i]), nums[i]); min=Math.min(Math.min(tmp*nums[i], min*nums[i]), nums[i]); ans=Math.max(ans, max); } return ans; } // public static void main(String[] args) { // int[] a = {2,-1,1,1}; // System.out.print(maxProduct(a)); // // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解