C++求最大子序列问题


//最大子序列求解问题,并加入了一个计时器,输出的是最大子序列和,最大子序列的起始下表
#include<iostream>
#include<vector>
#include<time.h>
using namespace std;
int *maxSubSum(const vector<int> &a)
{
 int* ans = new int[2];
 int maxSum = 0, thisSum = 0, q = 0;
 for (int j = 0;j < a.size();j++)
 {
  thisSum += a[j];
  if (thisSum > maxSum) {
   maxSum = thisSum;
  }
  else if (thisSum < 0) {
   thisSum = 0;
   q = j;
  } 
 }
 ans[0] = maxSum;
 ans[1] =q;
 return ans;
}
int main() {
 clock_t start, finish;
 double totaltime;
 start = clock();
 int Sum;
 cout << "输入你需要输入的序列长度" << endl;
 cin >> Sum;
 vector<int> a2(Sum);
 cout << "请输入你的序列" << endl;
 for (int i = 0;i < Sum;i++) {
  cin >> a2[i];
 }
 int *qr = maxSubSum(a2);
 cout << "最大子序列和为:"<<qr[0] << endl;
 cout << "子序列起始位置为:" << qr[1] << endl;
 finish = clock();
 totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
 cout << "此程序的运行时间为" << totaltime << "秒!" << endl;
 system("pause"); //getchar();
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值