鱼C论坛

 找回密码
 立即注册
查看: 227|回复: 1

使用双指针写,求一个数组子序列的最大值,并输出起始位置,根据下方代码修改

[复制链接]
发表于 2024-2-6 21:16:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int N=1e5+5;
  4. int a[N];
  5. int cnt[N];
  6. int res=-1e9;
  7. void solve()
  8. {
  9.     int n;
  10.     cin>>n;
  11.     cout<<n<<endl;
  12.     for(int i=1;i<=n;i++)cin>>a[i];
  13.     int sum=0;
  14.     int i,j;
  15.     for(i=1,j=2;i<=n,j<=n;i++)
  16.     {
  17.         sum+=a[i];
  18.         while(i<=j)
  19.         {
  20.             if(sum>res)
  21.             {
  22.                 res=sum;
  23.                 sum+=a[j];
  24.             }
  25.             j++;
  26.         }
  27.         j=i+1;
  28.     }
  29.     cout<<sum<<endl;
  30.     cout<<i<<" "<<j;
  31.    
  32. }
  33. int main()
  34. {
  35.     int t;
  36.     t=1;
  37.     while(t--)
  38.     {
  39.         solve();
  40.     }
  41. }
复制代码
我写的双指针不对,怎么修改
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-2-6 21:16:22 | 显示全部楼层
双指针法通常用于解决数组相关的问题,可以通过两个指针在数组上移动,从而找到满足条件的子序列。

根据你提供的代码,我来修改一下,使用双指针求解一个数组的子序列的最大值,并输出起始位置。

  1. #include<iostream>
  2. using namespace std;

  3. const int N = 1e5 + 5;
  4. int a[N];

  5. int main() {
  6.     int n;
  7.     cin >> n;
  8.     for (int i = 0; i < n; i++) {
  9.         cin >> a[i];
  10.     }

  11.     int left = 0, right = 0;  // 左右指针
  12.     int sum = 0;  // 当前子序列的和
  13.     int maxSum = -1e9;  // 最大的子序列和
  14.     int start = 0;  // 最大和子序列的起始位置

  15.     while (right < n) {
  16.         // 向右移动右指针,扩展子序列
  17.         sum += a[right];
  18.         if (sum > maxSum) {  // 更新最大子序列和及起始位置
  19.             maxSum = sum;
  20.             start = left;
  21.         }
  22.         right++;

  23.         // 如果当前子序列和为负数,则舍弃当前子序列,重新从下一个位置开始计算
  24.         if (sum < 0) {
  25.             sum = 0;
  26.             left = right;
  27.         }
  28.     }

  29.     cout << "最大子序列的起始位置:" << start << endl;
  30.     cout << "最大子序列的和:" << maxSum << endl;

  31.     return 0;
  32. }
复制代码


这段代码通过双指针移动的方式,寻找子序列的最大和,并输出起始位置。在每次向右移动右指针时,我们会更新当前子序列的和,并判断是否需要更新最大子序列和及其起始位置。如果当前子序列和为负数,则舍弃当前子序列,重新从下一个位置开始计算。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 21:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表