Lincode.41 maximum sub-array, lincode.41 sub-array
Maximum sub-array
- Description
- Notes
- Data
- Evaluation
Given an integer array, find a subarray with the largest sum and return the largest sum.
Notes
The sub-array must contain at least one number.
Have you ever encountered this question during a real interview? Yes, which company asked you this question? Airbnb Amazon LinkedIn Cryptic Studios Dropbox Apple Epic Systems TinyCo Yelp Hedvig Zenefits Uber Snapchat Yahoo Microsoft Bloomberg Facebook Google Twitter
Thank you for your feedback.
Example
Returns an array.[−2,2,−3,4,−1,2,1,−5,3]
, The Child array that meets the requirements is[4,−1,2,1]
, And its maximum sum is6
Challenges
Requires that the time complexity be O (n)
TagGreedy LinkedIn array LintCode copyright ownership sub-array Enumeration Method
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 s=nums.size(); int res=nums[0]; int cn=0; for(int i =0;i<s;i++){ cn+=nums[i]; if(res<cn) res=cn; if(cn<0) cn=0; } return res; }};