• 连续子数组的最大和


       1:  /*
       2:  @@
       3:      Author:    Justinzhang
       4:      Email:    uestczhangchao@gmail.com
       5:      time:    2012-9-1 21:40:13
       6:      desc:    find the max sum of sub arrys; This file was created at an earlier time; 
       7:              At that time, i didn't read the programming perls, in that book, there is a detailed
       8:              discussion about this problem. The fastest algrithm can solve it in O(n) time;
       9:              So if have spare time, read more of it.
      10:  @@
      11:  */
      12:   
      13:  #include <iostream>
      14:  #include <vector>
      15:  #include <algorithm>
      16:  #include <iomanip>
      17:  using namespace std;
      18:   
      19:  template<class type> 
      20:  type getMax(type param1, type param2)
      21:  {
      22:      return (param1>param2 ? param1 : param2);
      23:  }
      24:   
      25:  template<class type> type find_max_sum_of_subarray(vector<type> vec)
      26:  {
      27:      type maxSum = 0;
      28:      type curMaxSum = 0;
      29:      for(unsigned int i=0; i < vec.size(); i++)
      30:      {
      31:          curMaxSum += vec[i];
      32:          curMaxSum = getMax(0, curMaxSum);
      33:          maxSum = getMax(maxSum, curMaxSum);
      34:      }
      35:      return maxSum;
      36:  }
      37:   
      38:   
      39:  int main()
      40:  {
      41:      int array[] = {-2, 5, 3,-6, 44, -8, 16};
      42:      /* /!\ note that: to use array to initialize vector, the second parameter is the length of array,
      43:         not the length of array minus 1.
      44:      */
      45:      vector<int> vec(array,array+(sizeof array / sizeof(int)));
      46:      cout << "find_max_sum_of_subArray: " << find_max_sum_of_subarray<int>(vec) << endl;
      47:      return 0;
      48:  }
  • 相关阅读:
    栈和其他寄存器大小
    checksec的安装及初步使用(新版)
    KMP算法之Next数组详解
    向上取整的三种方法
    C++STL(Standard Template Library,即标准模版库)——Map容器
    JS基础语法一
    JS函数学习
    JS对象学习(二)
    JavaStript对象学习(一)
    CSS3新特性学习(2)
  • 原文地址:https://www.cnblogs.com/justinzhang/p/2667178.html
Copyright © 2020-2023  润新知