Chapter III Report on the machine algorithm

1. Practice topic

7-2 and the maximum sub-segment (40 minutes)

Given n integer (possibly negative) consisting of a sequence of a [1], a [2], a [n] a [3], ...,, find the sequence, such as a [i] + a [i + 1] + ... + a [j] and the maximum value of the sub-segments. When given are negative integer, is defined as 0 and the sub-segments. The time requirements of the algorithm complexity is O (n).

 

2. Description of the problem

Topic and seeking the maximum field, and requires time complexity is O (n), should the use of dynamic programming able to save the previous calculation result, thereby reducing the time complexity.

 

3. Algorithm Description

The most important use of dynamic programming is to write the dynamic programming recursion, temp [i] = max {b [i-1] + a [i], a [i]} (1 <= i <= n), wherein temp is the role and the current record, if the current sum is greater than the sum of the recording medium, the maximum sum is the final output.

 1 public static int MaxSum(int n, int[] a) {
 2         int sum = 0, temp = 0;
 3         for (int i = 1; i <= n; i++) {
 4             if (temp > 0)
 5                 temp += a[i];
 6             else
 7                 temp = a[i];
 8             if (temp > sum)
 9                 sum = temp;
10         }
11         return sum;
12 }
Algorithm code

 

4. The time and complexity of the spatial analysis algorithm

Time Complexity: Algorithms for only one cycle, and therefore is O (n)

Space complexity: the algorithm used in a large space and the original auxiliary sequence, etc., so as O (n)

 

5. experiences

The practice of using the main topics algorithms are dynamic programming, the use of which the most important is to write recursive, written after the recursive algorithm also good solution. At the same time, the general use of dynamic programming to the secondary array (space), can reduce the time complexity, improve the efficiency of the algorithm.

Guess you like

Origin www.cnblogs.com/Daylight-Deng/p/11707273.html