您的位置:首页 > 其它

求连续子数组的最大和与最大积

2013-11-30 15:27 176 查看

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

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。
思路一:求一个数组的最大子数组和,如此序列1, -2, 3, 10, -4, 7, 2, -5,我想最最直观也是最野蛮的办法便是,三个for循环三层遍历,求出数组中每一个子数组的和,最终求出这些子数组的最大的一个值。记Sum[i, …, j]为数组A中第i个元素到第j个元素的和(其中0 <= i <= j < n),遍历所有可能的Sum[i,
…, j],那么时间复杂度为O(N^3)。
代码如下:

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,那么最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。
所有的东西都在以下两行,即:
b  :  0  1  -1  3  13   9  16  18  13  
sum:  0  1   1  3  13  13  16  18  18
其实算法很简单,当前面的几个数,加起来后,b<0后,把b重新赋值,置为下一个元素,b=a[i]。当b>sum,则更新sum=b;若b<sum,则sum保持原值,不更新.
代码如下:

[cpp]
view plaincopy

#include <iostream.h>  
using namespace std;  
  
int maxSum(int* a, int n)  
{  
    int sum=a[0];  
    int b=0;  
      
    for(int i=0; i<n; i++)  
    {  
        if(b<0)             
            b=a[i];  
        else  
            b+=a[i];  
        if(sum<b)  
            sum=b;  
    }  
    return sum;  
}  
  
int main()  
{  
    int a[10]={1, -2, 3, 10, -4, 7, 2, -5};  
    cout<<maxSum(a,8)<<endl;  
    return 0;  


算法 2

//Algorithm 1:时间效率为O(n*n*n)  
int MaxSubsequenceSum1(const int A[],int N)  
{  
    int ThisSum=0 ,MaxSum=0,i,j,k;  
    for(i=0;i<N;i++)  
        for(j=i;j<N;j++)  
        {  
            ThisSum=0;  
            for(k=i;k<j;k++)  
                ThisSum+=A[k];  
              
            if(ThisSum>MaxSum)  
                MaxSum=ThisSum;  
        }  
        return MaxSum;  
}  
 

给定一个整型数足a,求出最大连续子段的乘积,比如 1, 2, -8, 12, 7则输出12 * 7 = 84

代码如下:

[html]
view plaincopy

// maxProduct.cpp : 定义控制台应用程序的入口点。  
//  
  
#include "stdafx.h"  
#include <iostream>  
#include   <stdlib.h>   
#include   <stdio.h>   
using namespace  std;  
  
  
  
// 子数组的最大乘积  
int MaxProduct(int *a, int n)  
{  
    int maxProduct = 1; // max positive product at current position  
    int minProduct = 1; // min negative product at current position  
    int r = 1; // result, max multiplication totally  
  
    for (int i = 0; i < n; i++)  
    {  
        if (a[i] > 0)  
        {  
            maxProduct *= a[i];  
            minProduct = min(minProduct * a[i], 1);  
        }  
        else if (a[i] == 0)  
        {  
            maxProduct = 1;  
            minProduct = 1;  
        }  
        else // a[i] < 0  
        {  
            int temp = maxProduct;  
            maxProduct = max(minProduct * a[i], 1);  
            minProduct = temp * a[i];  
        }  
  
        r = max(r, maxProduct);  
    }  
  
    return r;  
}  
  
int _tmain(int argc, _TCHAR* argv[])  
{  
    int a[]={1, -2, -3,0,5};  
    int result = MaxProduct(a,5);  
    cout<<result<<endl;  
    system("pause");  
    return 0;  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法