Lintcode.44 minimum sub-array, lintcode.44 Array
Minimum Child Array
- Description
- Notes
- Data
- Evaluation
Given an integer array, find a child array with the smallest sum. Returns the smallest sum of values.
Notes
The sub-array contains 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.[1,-1,-2, 1], Return-3
TagLintCode Copyright All Rights Reserved greedy sub-array Brute Force
class Solution {public: /* * @param nums: a list of integers * @return: A integer indicate the sum of minimum subarray */ int minSubArray(vector<int> &nums) { // write your code here int s=nums.size(); int res=nums[0]; for(int i=0;i<s;i++) { int cn=nums[i]; if(cn<res) res=cn; for(int j=i+1;j<s;j++) { cn+=nums[j]; if(cn<=res) res=cn; } } return res; }};
Greedy
class Solution {public: /* * @param nums: a list of integers * @return: A integer indicate the sum of minimum subarray */ int minSubArray(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; }};