Time to prove safety offer 30. efficiency and maximum continuous subarray

Title Description

HZ occasionally get some professional issues to flicker those non-computer science students. After the test group will finish today, he spoke up: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum and continuous sub-vector when the vector is a positive whole number, the problem solved. However, if the vector contains a negative number, it should contain a negative number, and expect a positive number next to it would make up for it? For example: {6, -3, -2,7, -15,1,2,2}, and the maximum successive sub-vectors of 8 (beginning from 0, up to the third). To an array and returns its maximum continuous subsequence and you will not be fooled him live? (Sub-vector length is at least 1)
Wrong Solutions:
public class FindGreatestSumOfSubArray {
    
 public int FindGreatestSumOfSubArray(int[] array) {
    
    int result=0;
    if (array.length==1) {
        return array[0];
    }
    else {
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            int sum=0;
            while(i<j) {
                sum+=array[i];
            }
          if (sum>result) {
            result=sum;
        }
     }
  } 
}      
     return result;
                         }

 

Correct problem-solving ideas:
 
Using dynamic programming
F (i): in array [i] is the last element of the subarray and the maximum value, the relative position of the elements of the same subarray
F(i)=max(F(i-1)+array[i] , array[i])
res: All sub-arrays and the maximum
res=max(res,F(i))

The array of [6, -3, -2, 7, -15, 1, 2, 2]
Initial state:
    F(0)=6
    res=6
i=1:
    F(1)=max(F(0)-3,-3)=max(6-3,3)=3
    res=max(F(1),res)=max(3,6)=6
i=2:
    F(2)=max(F(1)-2,-2)=max(3-2,-2)=1
    res=max(F(2),res)=max(1,6)=6
i=3:
    F(3)=max(F(2)+7,7)=max(1+7,7)=8
    res=max(F(2),res)=max(8,6)=8
i=4:
    F(4)=max(F(3)-15,-15)=max(8-15,-15)=-7
    res=max(F(4),res)=max(-7,8)=8
And so on
The final value of 8 res
public  int FindGreatestSumOfSubArray(int[] array) {
             int res = array[0]; //记录当前所有子数组的和的最大值
             int max=array[0];   //包含array[i]的连续数组最大值
             for (int i = 1; i < array.length; i++) {
                 max=Math.max(max+array[i], array[i]);
                 res=Math.max(max, res);
             }
             return res;
     }

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11272826.html