Problem Description:
Computes the sum of the largest subsequence of a given array
Analysis:
There are three ways to do this:
1, Scan 3 times, you can calculate the sum of all sub-sequences, but the complexity of n^3.
2, Scan 2 times, calculate with any element start and, if greater than the current maximum value will pay it, the complexity of n^2.
3, scan again, calculate the value of any element start, if less than 0 clear zero, otherwise continue to add.
Code implementation:
package c02;/** * @project: datastructureandalgorithmanalysis * @filename: maxsubsum * @version: 0.10 * @author: jimmy han * @date: 21:35 2015/7/7 * @comment: calculates the back and, if negative, the starting point for each element, and then restarts the calculation * @result: 10 */public class maxsubsum { public static void main (String [] args) { int[] arr = {-1, 3, 2, -3, -1, 4, 5}; system.out.println ( Maxsubsum (arr)); } public static int maxsubsum ( int[] a) { int maxsum = 0, Thissum = 0; for (int j = 0; j < a.length; j++) { thissum += a[j]; if (thissum > maxsum) maxSum = Thissum; else if (thisSum < 0) thissum = 0; } return maxsum; }}
Computes the sum of the largest subsequence of an array