zoukankan      html  css  js  c++  java
  • (微软100题)3.求子数组的最大和

    #include <iostream>
    using namespace std;
    /*3.求子数组的最大和
    题目:
    输入一个整形数组,数组里有正数也有负数。
    数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
    求所有子数组的和的最大值。要求时间复杂度为O(n)。
    例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
    因此输出为该子数组的和18。
    ANSWER: 
    A traditional greedy approach.
    Keep current sum, slide from left to right, when sum < 0, reset sum to 0.
    */
    int maxSubarray(int a[], int size)
    {
    	if (size<=0) 
    		cout<<("error array size");
    	int sum = 0;
    	int max = - (1 << 31);
    	int cur = 0;
    	while (cur < size) 
    	{
    		sum += a[cur++];
    		if (sum > max) 
    		{
    			max = sum;
    		} else if (sum < 0) 
    		{
    			sum = 0;
    		}
    	}
    	return max;
    }
    
    void main()
    {
    	int test[8] = {1,-2,3,10,-4,7,2,-5};
    	cout<<maxSubarray(test,8)<<endl;
    	system("pause");
    }

  • 相关阅读:
    感知机学习笔记
    NOIP 模拟19
    NOIP 模拟17
    NOIP模拟14-16
    「动态规划」-数位dp专题
    8.5 NOIP 模拟测试 13
    8.3 NOIP 模拟12题解
    8.3 NOIP CE反思
    「分治」-cdq分治
    8.1 NOIP模拟11
  • 原文地址:https://www.cnblogs.com/byfei/p/6389847.html
Copyright © 2011-2022 走看看