PTA 01-复杂度2 Maximum Subsequence Sum (25分)
題目地址
https://pta.patest.cn/pta/test/16/exam/4/question/663
?
5-1?Maximum Subsequence Sum???(25分)
Given a sequence of?KK?integers {?N_1N?1??,?N_2N?2??, ...,?N_KN?K???}. A continuous subsequence is defined to be {?N_iN?i??,?N_{i+1}N?i+1??, ...,?N_jN?j???} where?1 \le i \le j \le K1≤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?KK?(\le 10000≤10000). The second line contains?KK?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?ii?and?jj?(as shown by the sample case). If all the?KK?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 -21Sample Output:
10 1 4/*評測結(jié)果 時(shí)間 結(jié)果 得分 題目 編譯器 用時(shí)(ms) 內(nèi)存(MB) 用戶 2017-07-08 15:45 正在評測 0 5-1 gcc 無 無 測試點(diǎn)結(jié)果 測試點(diǎn) 結(jié)果 得分/滿分 用時(shí)(ms) 內(nèi)存(MB) 測試點(diǎn)1 答案正確 13/13 2 1 測試點(diǎn)2 答案正確 2/2 1 1 測試點(diǎn)3 答案正確 2/2 1 1 測試點(diǎn)4 答案正確 2/2 1 1 測試點(diǎn)5 答案正確 2/2 1 1 測試點(diǎn)6 答案正確 2/2 1 1 測試點(diǎn)7 答案錯(cuò)誤 0/1 1 1 測試點(diǎn)8 答案正確 1/1 3 1不知道什么情況,卡了一個(gè)測試點(diǎn) */ #include<stdio.h> int main() {int i,k;int getNum,lastGetNum=-1,max=0;int tempfirst=0,first=0,last=0;int allNegtiveFlag=1,sum=0;scanf("%d",&k);for(i=0;i<k;i++){ scanf("%d",&getNum);if(getNum>=0) allNegtiveFlag=0;if (i==0) first=getNum;if (sum==0 && getNum>0){ // if(lastGetNum!=0)tempfirst=getNum;}sum+=getNum;if (sum<0) sum=0;if (sum>max){max=sum;first=tempfirst;last=getNum;} // lastGetNum=getNum;if(i==k-1 && max==0 && allNegtiveFlag==1)last=getNum;}if(max==0 && allNegtiveFlag==0){first=0;last=0;}printf("%d %d %d",max,first,last); }
轉(zhuǎn)載于:https://www.cnblogs.com/gk2017/p/7140502.html
總結(jié)
以上是生活随笔為你收集整理的PTA 01-复杂度2 Maximum Subsequence Sum (25分)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android App性能測试
- 下一篇: Python之路 day1 基础1 变