zoukankan      html  css  js  c++  java
  • 连续子数组的最大和

    题目:输入一个整形数组,数组里有正数也有负数。组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。

    思路:当我们加上一个正数时,和会增加;当我们加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数将会减少接下来的和,用一个变量记录最大的和,最后返回即可。

     1 #include<stdio.h>
     2 #include "stdafx.h"
     3 
     4 bool g_InvalidInput = false;
     5 
     6 int FindGreatestSumOfSubArray(int *pData, int nLength)
     7 {
     8     if((pData == NULL) || (nLength <= 0))
     9     {
    10         g_InvalidInput = true;
    11         return 0;
    12     }
    13     
    14     g_InvalidInput = false;
    15     
    16     int nCurSum = 0;
    17     int nGreatestSum = 0x80000000;
    18     for(int i = 0; i < nLength; ++i)
    19     {
    20         if(nCurSum <= 0)
    21             nCurSum = pData[i];
    22         else
    23             nCurSum += pData[i];
    24         
    25         if(nCurSum > nGreatestSum)
    26             nGreatestSum = nCurSum;
    27     }
    28     
    29     return nGreatestSum;
    30 }
    31 
    32 int main()
    33 {
    34     int data[] = {1, -2, 3, 10, -4, 7, 2, -5};
    35     int nLength = sizeof(data)/ sizeof(int);
    36     int result = FindGreatestSumOfSubArray(data, nLength);
    37     bool expectedFlag = false;
    38     if(expectedFlag == g_InvalidInput)
    39         printf("%d", result);
    40     else
    41         printf("Failed");
    42     return 0;
    43 }

  • 相关阅读:
    TEXT 6 Travelling with baggage
    TEXT 4 A question of standards
    TEXT 3 Food firms and fat-fighters
    linux——DNS服务器配置
    NISP视频知识点总结
    词根生词要打印加上汉译
    琐碎的总结 css jQuery js 等等。。。
    css 描述css reset的作用和用途。
    css--block formatting context
    《javascript高级程序设计》 第25章 新兴的API
  • 原文地址:https://www.cnblogs.com/sankexin/p/5633588.html
Copyright © 2011-2022 走看看