zoukankan      html  css  js  c++  java
  • 01-复杂度2. Maximum Subsequence Sum (25)

    Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

    Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

    Input Specification:

    Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

    Output Specification:

    For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

    Sample Input:
    10
    -10 1 2 3 4 -5 -23 3 7 -21
    
    Sample Output:
    10 1 4
    
    
    
     
    1
    import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 public class Main 6 { 7 static private int K; 8 static private int[] list; 9 public static void main(String[] args) throws IOException 10 { 11 // System.out.println("..."); 12 BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); 13 String line=buf.readLine(); 14 K=Integer.parseInt(line); 15 list=new int[K]; 16 line=buf.readLine(); 17 String[] temp=line.split(" "); 18 for(int i=0;i<K;i++) 19 list[i]=Integer.parseInt(temp[i]); 20 // 判断是否都是0 21 boolean flag=false; 22 for(int i=0;i<K;i++) 23 { 24 if(list[i]>=0) 25 { 26 flag=true; 27 break; 28 } 29 } 30 if(flag==false) 31 { 32 System.out.print(0+" "+list[0]+" "+list[K-1]); 33 return; 34 } 35 36 int x=0; 37 int y=0; 38 int t1=0; 39 int t2=0; 40 int t3=0; 41 for(int i=0;i<K;i++) 42 { 43 if(x==0&&list[i]>=0) 44 t1=i; 45 x=Math.max(x+list[i],0); 46 if(x>y) 47 { 48 t2=t1; 49 t3=i; 50 } 51 y=Math.max(y, x); 52 } 53 System.out.print(y+" "+list[t2]+" "+list[t3]); 54 } 55 }
  • 相关阅读:
    TongJI Online Judge预赛(3): Game
    堆栈小应用:配对
    在.net中使用Udp协议创建简单的聊天程序
    TongJI Online Judge预赛(2): LOVE LETTER
    全排列问题之递归求解
    如何打造RSS阅读器
    Html 常用标志总结
    实现页面的分帧显示
    每天OnlineJudge之 “数素数”
    文本编辑器中,如何设计 撤销/重复栈
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4399650.html
Copyright © 2011-2022 走看看