Java动态规划解决最大子数组问题,线性时间复杂度。(算法导论4.1)

package 最大子数组;

import java.util.Arrays;

/*
 * 动态规划方法解决最大子数组问题
 * */
public class Solution {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		int[] arr = new int[] {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4};
		int[] result = new int[3];
		System.out.println(Arrays.toString(findMaxSubArray(arr)));
	}
	
	static int[] findMaxSubArray(int[] arr) {
		int thisMax = Integer.MIN_VALUE / 2,resultMax = Integer.MIN_VALUE / 2;
		int leftIndex = 0 , rightIndex = 0,leftIndexTemp = 0, rightIndexTemp = 0;
		for(int i = 0;i thisMax + arr[i])
			{
				thisMax = arr[i];
				leftIndexTemp = i;
				rightIndexTemp = i;
			}
			else {
				thisMax += arr[i];
				rightIndexTemp ++;
			}
			
			if(thisMax > resultMax) {
				resultMax = thisMax;
				leftIndex = leftIndexTemp;
				rightIndex = rightIndexTemp;
			}
		}
		return new int[] {leftIndex,rightIndex,resultMax};
		
	}

}

 

你可能感兴趣的:(算法导论)