Maximum sub-sequence problem: Given an integer sequence a1,a2,a3 ... An (may have a negative number), to find the a1~an of a maximum subsequence Ai~aj and.

Source: Internet
Author: User
Tags stub

This is a PPTV2015 year campus recruitment written questions.


Example: The result of one program running

Please enter sequence length n:
6
Please enter n sequence values:
-1 3-2 4 5-6
The substring is:
START ... 2
End ..... 5
Maxsum is 10.0



/*
Problem
* Maximum sub-sequence problem: Given an integer sequence a1,a2,a3 ... An (may have a negative number), to find the a1~an of a maximum subsequence Ai~aj and.
*
*/


Import Java.util.Scanner;
public class Pptv_bishi {
The double loop method solves the time complexity O (n*3).
public static void Main (string[] args) {
TODO auto-generated Method Stub
int n;
System.out.println ("Please enter sequence length n:");
Scanner in=new Scanner (system.in);
N=in.nextint ();
System.out.println ("Please enter n sequence values:");
int [] arr=new int[n+1];
for (int i=1;i<=n;i++) {//input sequence an.
Arr[i]=in.nextint ();
}
In.close ();
Double sum=0;//records the largest subsequence and.
Double temp=0;
int low=0,high=0;
for (int i=1;i<=n;i++) {
for (int j=i;j<=n;j++) {
Temp=dosearch (I,j,arr);
if (temp>sum) {
Sum=temp;
Low=i;
High=j;
}
}
}
SYSTEM.OUT.PRINTLN ("The substring is: \nstart ..." +low+ "\nend ..." +high+ "\nmaxsum is" +sum);


}


private static double dosearch (int low,int high,int[] arr) {
TODO auto-generated Method Stub
Double value=0;

for (int i=low;i<=high;i++) {
Value+=arr[i];
}
return value;


}
}

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.