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 }
  • 相关阅读:
    使用xca生成SSL证书
    在 Apache error_log 中看到多个信息,提示 RSA server certificate CommonName (CN) 与服务器名不匹配(转)
    SSL/TLS 高强度加密: 常见问题解答
    JAVA 集合操作总结
    VUE 微信开发
    实战 ant design pro 中的坑
    Spring boot 配置 mybatis xml和动态SQL 分页配置
    VUE打包上线优化
    VUE中如何优雅的动态绑定长按事件
    用C自撸apache简易模块,搭建图片处理服务器。
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4399650.html
Copyright © 2011-2022 走看看