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

    题目描写叙述

    输入一个数组,有正数也有负数,求连续子数组的最大和。


    解题思路

    典型动态规划

    设f(i) 表示 以i位置结尾的子数组和,那么有:

    递推式:f(i) = max{ f(i-1) + array[i],  array[i]  }

    初值:f(0) = array[0]


    实现代码


    class Solution {
    public:
        int FindGreatestSumOfSubArray(vector<int> array) {
            
            if(array.empty())
                return 0;
            
            int retMax=INT_MIN;
            int len = array.size();
            vector<int> ans(len,INT_MIN);
            
            ans[0] = array[0];
            retMax = ans[0];
            
            for(int i=1; i<len; i++)
            {
            	ans[i] = getMax( (ans[i-1] + array[i]), array[i]);  
                
                if(ans[i] > retMax)
                    retMax = ans[i];
            }
            
            return retMax;
        
        }
        
        int getMax(int a, int b)
        {
        	return a>b?

    a:b; } };



  • 相关阅读:
    发光二极管
    续流二极管作用及工作原理
    python backtrace注意事项
    docker tips
    direct stdin and stdout
    python skill
    mysql comments
    python dict
    python list and tuple
    Python library
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/6802937.html
Copyright © 2011-2022 走看看