To prove safety offer 30. The maximum and continuous sub-array

30. The maximum and 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)

Ideas:

Dynamic programming, dp [i] represented by A [i] and the maximum contiguous subsequence ending

When the sequence is provided to A [i] and the maximum at the end, if the sequence length is 1, dp [i] = A [i],

1, and the sequence of adding the foregoing and A [i], i.e., dp [i] = dp [i - 1] If the sequence length is not + A [i]; therefore transfer equation: DP = max (A [ i], dp [i - 1 ] + A [i]);

In fact, by looking dp [i - 1] is greater than, if greater than 0, it must be combined with the previous sequence, not in front of the sequence is less than 00 or less than 0; therefore the state transition equation can be changed to: dp [ ? i] = dp [i - 1]> 0 dp [i - 1] + A [i]: A [i];

. 1  public  class Solution {
 2      public  int FindGreatestSumOfSubArray ( int [] Array) {
 . 3          // dynamic programming, dp [i] represented by A [i] at the end of the maximum and contiguous subsequence
 . 4          // DP [I] = max (A [I], DP [I -. 1] + A [I]) 
. 5          int [] DP = new new  int [be array.length];
 . 6          DP [ 0 ] = Array [ 0 ];
 . 7           int max = - . 1 << 30 ;
 . 8          for ( int I = . 1 ; I <be array.length; I ++ ) {
 . 9             // dp[i] = Math.max(array[i], dp[i - 1] + array[i]);
10             dp[i] = dp[i - 1] > 0 ? dp[i - 1] + array[i] : array[i];
11             max = max > dp[i] ? max : dp[i];
12         }
13         return max;
14     }
15 }

 

Guess you like

Origin www.cnblogs.com/hi3254014978/p/12589314.html