#题目java
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.code
其实无论是最大连续自序列和仍是乘积,关键的一个概念是定义一个变量叫作 “包含当前值的最大连续序列值(和/乘积)”,举例来讲curMaxit
这个值的存在使得包含下一个位置的最大连续序列值的求解成为可能,以最大连续自序列求和为例,io
curMax(x+1) = max(A[x+1], curMax(x) + A[X])ast
对于最大连续自序列乘积,须要纪录两个,一个是包含当前值的最大连续子序列乘积, 一个是包含当前值的最小自序列乘积class
curMax(x + 1) = Math.max(curMax(x)*A[x], curMin(x)*A[x], A[x]) curMin(x + 1) = Math.min(curMax(x)*A[x], curMin(x)*A[x], A[x])变量
由于包含当前值的最大值(最小值)只能由这三种可能构成co
最大连续自序列和block
public class Solution { public int maxSubArray(int[] A) { int curMax = A[0]; int max = A[0]; for (int i = 1; i < A.length ; i++) { curMax = Math.max(A[i], curMax + A[i]); max = Math.max(max, curMax); } return max; } }
最大连续子序列乘积return
public class MaxProductSubArray { public int maxProduct(int[] A) { int curMax = A[0]; int curMin = A[0]; int max = A[0]; for(int i = 1; i < A.length; i++) { // 注意这里先存起来,下面要在更新以后再用一次 int temp = curMax * A[i]; curMax = Math.max(A[i], Math.max(curMax * A[i], curMin * A[i])); curMin = Math.min(A[i], Math.min(temp, curMin * A[i])); max = Math.max(curMax, max); } return max; } }
d[i][j]表示A[0...i],B[0...j],而且以A[i]和B[j]结尾的最长公共连续子串的长度
d[i][j] = d[i-1][j-1] if A[i] == B[j] d[i][j] = 0 if A[i] != B[j]