标签:maximum product suba dynamic programming
描述:
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.
思路:
0.动态规划问题,和求最大连续和maximum subarray类似,但感觉比求最大连续和复杂的多
1.以0为分割元素获得一系列的区间
2.对每一个区间求最大值
3.具体到每一个区间,顺序查找一遍寻找最大的序列,逆序查找一遍寻找最大的序列,求顺序或逆序查找的最大值
4.注意:(tempCount1&1) == 1)可以节省好多时间,用%2==1就不行
代码:
public int maxProduct(int[] nums) {
if (nums == null)
return 0;
if (nums.length == 0)
return 0;
if (nums.length == 1)
return nums[0];
List<Integer> list = new ArrayList<Integer>();
list.add(-1);
for (int i = 0; i < nums.length; i++) {//以0为分割元素获得一系列的区间
if (nums[i] == 0)
list.add(i);
}
list.add(nums.length);
int len = list.size();
int max = 0, tempMax = 0;
for (int i = 0; i < len - 1; i++) {//对每一个区间求最大值
tempMax = getMax(nums, list.get(i), list.get(i + 1));
max = max > tempMax ? max : tempMax;
}
return max;
}
public int getMax(int nums[], int start, int end) {
if (end - start <= 2)//==2时说明区间除了0外只有一个元素,<2说明区间只有一个元素0
{
if(start!=nums.length-1)
return nums[start + 1];
else
return nums[start];//最后一个元素
}
int sum = 1;
int count = 0;
for (int i = start + 1; i < end; i++) {
sum *= nums[i];
if (nums[i] < 0)
count++;
}
int tempSum = sum;
int tempCount = count;
for (int i = start + 1; i < end; i++) {//顺序查找一遍寻找最大的序列
if (tempSum < 0) {
if (nums[i] < 0 &&(tempCount&1) == 1) {//(tempCount1&1) == 1)可以节省好多时间,用%2==1就不行
tempSum /= nums[i];
break;
} else {
tempSum /= nums[i];
}
} else
break;
}
int tempSum1 = sum;
int tempCount1 = count;
for (int i = end - 1; i > start; i--) {//逆序查找一遍寻找最大的序列
if (tempSum1 < 0) {
if (nums[i] < 0 && (tempCount1&1) == 1) {//(tempCount1&1) == 1)可以节省好多时间,用%2==1就不行
tempSum1 /= nums[i];
break;
} else {
tempSum1 /= nums[i];
}
} else
break;
}
int max = tempSum > tempSum1 ? tempSum : tempSum1;//求顺序或逆序查找的最大值
return max;
}leetcode_Maximum Product Subarray
标签:maximum product suba dynamic programming
原文地址:http://blog.csdn.net/mnmlist/article/details/45815563