zoukankan      html  css  js  c++  java
  • 【编程练习】求数组和最大的子数组

    上代码先:

    问题代码来源:http://blog.csdn.net/v_JULY_v

    // MaxSum.cpp : 定义控制台应用程序的入口点。
    //
    //copyright@ July
    //July、updated,2011.05.25。
    
    
    #include "stdafx.h"
    #include <iostream> 
    using namespace std;
    
    int maxsum(int a[], int n)
    {
    	int max = a[0];//全负情况,返回最大数
    	int sum = 0;
    	for (int j = 0; j< n; j++)
    	{
    		if (sum >= 0)
    			sum = sum + a[j];	//如果加上某个元素,sum>=0 的话,就加
    		
    		else
    			sum = a[j];		//如果加上某个元素,sum<0 了,就不加
    		
    		if(sum > max)
    			max = sum;
    		
    	}
    
    	return max;
    
    }
    
    
    //Algorithm 4:时间效率为O(n)
    //同上述第一节中的思路3、和4。
    //《Data structures and Algorithm analysis in C》中实现。
    int MaxSubsequenceSum(const int A[],int N)
    {
    	int ThisSum,MaxSum,j;
    	ThisSum=MaxSum=0;
    	for(j=0;j<N;j++)
    	{
    		ThisSum+=A[j];
    		if(ThisSum>MaxSum)
    			MaxSum=ThisSum;
    		else if(ThisSum<0)
    			ThisSum=0;
    	}
    	return MaxSum;
    }
    
    int main()
    {
    	int a[]={-1,-2,-3,-4,10,1,-3};
    
    	cout<<maxsum(a,7)<<endl;
    	cout<<MaxSubsequenceSum(a,7)<<endl;
    	
    	getchar();
    	return 0;
    }
    
    


     

  • 相关阅读:
    Lucky Permutation Triple 构造
    HDU4283:You Are the One(区间DP)
    D. Match & Catch 后缀数组
    数学选讲 orz
    D
    一步一步线段树
    湖科大校赛第三题
    最大流部分
    bfs题目集锦
    hdu1429 bfs+状态压缩
  • 原文地址:https://www.cnblogs.com/wangyaning/p/7854031.html
Copyright © 2011-2022 走看看