zoukankan      html  css  js  c++  java
  • 面试题27:连续子数组的最大和

    注意:当函数输入无效时,返回为0,而子数组的和也有可能为0,为了区分,设置一个全局变量标记输入是否有效。

    思路用下表说明:


    代码:

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    bool bInvalidInput = false;//用全局变量标记是否为无效输入
    //求连续子数组的最大和
    int FindGreatestSumOfSubArray(int nArr[], int nLength)
    {
        if (nArr == NULL || nLength <=0)
        {
    		bInvalidInput = true;
    		return 0;
        }
    
        int nGreatestSum = 0x80000000;//记录连续子数组的最大和,初始值设置为很小的负数
    	int nCurrentSum = 0;
    	for (int i=0; i<nLength; i++)
    	{        
    		if (nCurrentSum <= 0)
    		{
                nCurrentSum = nArr[i];
    		}
    		else
    		{
    			nCurrentSum += nArr[i];
    		}
    
    		if (nCurrentSum > nGreatestSum)
    		{
    			nGreatestSum = nCurrentSum;
    		}
    	}
    	return nGreatestSum;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	int nArr1[8] = {1, -2, 3, 10, -4, 7, 2, -5};
    	int nGreatestSumOfSubArray1 = FindGreatestSumOfSubArray(nArr1, 8);
    	if (!bInvalidInput)
    	{
    		cout << "连续子数组的最大和为:" << nGreatestSumOfSubArray1 << endl;
    	}
    
    	int nArr2[8] = {-1, -2, -3, -10, -4, -7, -2, -5};
    	int nGreatestSumOfSubArray2 = FindGreatestSumOfSubArray(nArr2, 8);
    	if (!bInvalidInput)
    	{
    		cout << "连续子数组的最大和为:" << nGreatestSumOfSubArray2 << endl;
    	}
    	return 0;
    }
    
    
    运行结果:

  • 相关阅读:
    图像滤波
    直方图histeq
    直方图
    基于灰度变换的图像增强
    图像增强
    图像旋转和缩放
    图像点运算
    像素的连接与联通
    程序员进阶之算法练习(一)
    RxSwift 系列(二)
  • 原文地址:https://www.cnblogs.com/jiangu66/p/3214902.html
Copyright © 2011-2022 走看看