动态规划问题,
package com.dong.alg.dp;
/**
* 求连续子数组的最大和
* @author cuihd
*
*/
public class MaxSumOfSubArray {
public static void main(String[] args) {
int[] array = {1,3,-4,7,0,-1,2};
int result = getMaxSumOfSubArray(array);
System.out.println(result);
}
public static int getMaxSumOfSubArray(int[] array) {
if(null == array) {
throw new NullPointerException("参数array为null");
} else if(array.length <=0){
throw new RuntimeException("参数array为的size为0");
}
int result = array[0];
int sum = array[0];
for(int i=1;i<array.length;i++) {
if(sum > 0) {
sum = sum + array[i];
} else {
sum = array[i];
}
if(sum > result) {
result = sum;
}
}
return result;
}
}
package com.dong.alg.dp;
/**
* 求最长公共子串(字串为连续的)
* http://www.cnblogs.com/dartagnan/archive/2011/10/06/2199764.html
*/
public class MaxSubArray {
public static void main(String[] args) {
int[] tr = {1,2,3,4,7,9};
int[] td = {2,1,3,4,6,9,0,1,2,3,4};
int[] result = getMaxSubArray(tr,td);
if(null != result) {
for(int i : result) {
System.out.print(" " + i);
}
}
}
/**
* 把一个数组横向铺好,另一个数组纵向铺好,
* 然后在相等的元素上面做标记,连续时间最长的对角线就是最长的公共字串
* 1 2 3 4 7 9
*
2 0 1 0 0 0 0
1 1 0 0 0 0 0
3 0 0 1 0 0 0
4 0 0 0 2 0 0
6 0 0 0 0 0 0
9 0 0 0 0 0 1
0 0 0 0 0 0 0
1 1 0 0 0 0 0
2 0 2 0 0 0 0
3 0 0 3 0 0 0
4 0 0 0 4 0 0
*
* @param tr 需要横向铺的数组
* @param td 需要纵向铺的数组
* @return
*/
public static int[] getMaxSubArray(int[] tr,int[] td) {
int[] result = null;
int trLength = tr.length;
int tdlength = td.length;
int maxno = 0; //记录改公共字串的长度
int hangposition = -1; //记录数组td的位置,该位置为最长公共子串的最后一个元素
int lieposition = -1; //记录数组tr的位置,该位置为最长公共子串的最后一个元素
//注意,这里比较爱出错。纵向数组为二维数组的总行数,横向数组为二维数组的总列数
int[][] twodArray = new int[tdlength][trLength];
System.out.println("二维数组为: " + tdlength + "行" + trLength + "列");
for(int i = 0;i<tdlength;i++) {
for(int j=0;j<trLength;j++) {
if(tr[j] == td[i]) {
if(j-1 >= 0 && i-1>=0) {
twodArray[i][j] = twodArray[i-1][j-1] + 1;
if(twodArray[i][j] > maxno) {
maxno = twodArray[i][j];
hangposition = i;
lieposition = j;
}
} else {
twodArray[i][j] = 1;
}
}
}
}
//着行打印二维数组
for(int i = 0;i<tdlength;i++) {
for(int j=0;j<trLength;j++) {
System.out.print(" " + twodArray[i][j]);
}
System.out.println();
}
System.out.println(lieposition);
result = new int[maxno];
for(int i = lieposition - (maxno-1);i<=lieposition;i++) {
result[i] = tr[i];
}
return result;
}
}