41 最大子数组
原題網址:http://www.lintcode.com/zh-cn/problem/maximum-subarray/
給定一個整數數組,找到一個具有最大和的子數組,返回其最大和。
?注意事項
子數組最少包含一個數
? 樣例給出數組[?2,2,?3,4,?1,2,1,?5,3],符合要求的子數組為[4,?1,2,1],其最大和為6
挑戰?要求時間復雜度為O(n)
標簽? 貪心?領英?數組?LintCode 版權所有?子數組?枚舉法 ? 1 #include <iostream> 2 #include <vector> 3 #include <math.h> 4 using namespace std; 5 6 7 int maxSubArray(vector<int> &nums) //找整形數組的最大子數組; 8 { 9 int size=nums.size(); 10 int maxsum=nums[0]; 11 12 for (int i=0;i<size;i++) 13 { 14 int tempsum=0; 15 for (int j=i;j<size;j++) 16 { 17 tempsum=tempsum+nums[j]; 18 if (tempsum>maxsum) 19 { 20 maxsum=tempsum; 21 } 22 } 23 } 24 return maxsum; 25 26 27 42 }?
貪心法,時間復雜度O(n)
class Solution { public:/*** @param nums: A list of integers* @return: A integer indicate the sum of max subarray*/int maxSubArray(vector<int> &nums) {// write your code hereint size = nums.size();int max = nums[0];int nowm = 0;for (int i = 0; i < size; i++) {nowm += nums[i];if (nowm > max) {max = nowm;}if (nowm < 0) {nowm = 0;}}return max;} };參考網址:
1、https://blog.csdn.net/sinat_30440627/article/details/54924737
2、https://blog.csdn.net/linglian0522/article/details/70670801
轉載于:https://www.cnblogs.com/Tang-tangt/p/8632948.html
總結
- 上一篇: PHP5 ini配置文件优化
- 下一篇: git学习创建项目仓库