Computes the sum of the largest subsequence of an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.