Maximum Subarray
Description
Given an array of integers, find a contiguous subarray which has the largest sum.
Notice The subarray should contain at least one number.
Example Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Challenge
Can you do it in time complexity O(n)?
Link
Method
- keep tracking the running sum,
keeping tacking the max running sum for current and previous,
Once the current running sum < 0, running sum = 0, recaculate the running sum for rest- x
Example
- 1
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 if (nums.empty()) { return -1; } int n = nums.size(); int sum = 0; int maximum = INT_MIN; for (int i = 0; i < n; ++i) { sum += nums[i]; maximum = max(maximum, sum); sum = max(sum, 0); } return maximum; } };
Similar problems
x
Tags
x