标签:bar write ++ sum color you class log logs
Maximum Subarray
Given an array of integers, find a contiguous subarray which has the largest sum.
Given the array [?2,2,?3,4,?1,2,1,?5,3]
, the contiguous subarray [4,?1,2,1]
has the largest sum = 6
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 here int n = nums.size(); int ans = -1000000; int sum = 0; for(int i=0; i<n; i++) { sum += nums[i]; if(sum > ans) { ans = sum; } if(sum < 0) { sum = 0; //子串和为负数,丢掉 } } return ans; } };
LintCode - Maximum Subarray - Greedy Algorithm
标签:bar write ++ sum color you class log logs
原文地址:http://www.cnblogs.com/xumh/p/7698360.html