求某一数组内连续子数组的最大和
  yQAl4kecrO8W 2023年12月22日 149 0


题目描述:

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和 。

解法1 两层for循环…以下是代码

#include <stdio.h>
#include <stdlib.h>
int solution(int m, int arr[]){
    int result = 0;
    int i = 0;
    int nResTmp = 0;
    while(i < m)
    {
        result = 0;
        for(int j = i; j < m; ++j)
        {
            result += arr[j];
            if(nResTmp < result)
            {
                nResTmp = result;
            }
        }
        i++;
    }
    result = nResTmp;
    return result;
}

int main() {
    int n = 9;
    int arr = {-2,1,-3,4,-1,2,1,-5,4};
    int result = solution(n, &arr);
    printf("%d", result);
    return 0;
}

解法2 一层for循环…以下是代码

int solution(int m, int arr[]){
	int curSum=0;
	int maxSum=0;
	for(int i = 0 ;i < m; i++)
	{
		// 如果当前和小于等于0,那么舍弃掉它,从数组中的当前项开始累加
		if(curSum <= 0)
		{
			curSum = arr[i];
		}else // 否则当前和需要加上数组中的当前的项
		{
			curSum += arr[i];
		}
 	  // 每次计算后需要更新最大和
		if(curSum > maxSum)
			maxSum = curSum;
	}
}
输入示例

求某一数组内连续子数组的最大和_c++

输出结果
6


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月22日 0

暂无评论

推荐阅读
  BYaHC1OPAeY4   2024年05月08日   56   0   0 C++
  TKwJ4YzyA8uz   2024年05月17日   48   0   0 C语言
  V88gxnVgnp1F   2024年05月08日   92   0   0 C语言
  6Df3JnWQUC5m   2024年05月08日   86   0   0 C语言
  o1ZcTI9mJsxK   2024年05月08日   121   0   0 C语言
  6Df3JnWQUC5m   2024年05月17日   59   0   0 C语言
  oXKBKZoQY2lx   2024年05月17日   57   0   0 C++
yQAl4kecrO8W