Smallest subarray with sum greater than a given value
2014-06-22 09:51
399 查看
// Smallest subarray with sum gt value.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int smallestSubWithSum(int *arr, int len, int x) { int sum = 0; int startIdx = 0; int endIdx = 0; int minLen = len; for (int endIdx = 0; endIdx < len; endIdx++) { sum += arr[endIdx]; while (sum > x) { if (endIdx-startIdx+1 < minLen) { minLen = endIdx-startIdx+1; } sum -= arr[startIdx]; startIdx++; } } return minLen; } int _tmain(int argc, _TCHAR* argv[]) { int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = sizeof(arr1)/sizeof(arr1[0]); cout << smallestSubWithSum(arr1, n1, x) << endl; int arr2[] = {1, 10, 5, 2, 7}; int n2 = sizeof(arr2)/sizeof(arr2[0]); x = 9; cout << smallestSubWithSum(arr2, n2, x) << endl; int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = sizeof(arr3)/sizeof(arr3[0]); x = 280; cout << smallestSubWithSum(arr3, n3, x) << endl; return 0; }
相关文章推荐
- Smallest subarray with sum greater than a given value
- Find subarray with given sum
- Find subarray with given sum
- Find subarray with given sum
- Given an array of positive and negative integers find the first subarray with zero sum
- Subarray Sum to the given target value
- No sources that matches the given name (at 'layout_toLeftOf' with value '@id/
- more than one row with the given identifier was found
- 找不R文件切且报 no resource found that matches the given name(“at ' layout_above ' with value ' @id/text_p'
- Find Smallest Letter Greater Than Target
- LeetCode862. Shortest Subarray with Sum at Least K
- [LeetCode] Find Smallest Letter Greater Than Target 找比目标值大的最小字母
- Find Smallest Letter Greater Than Target
- LeetCode 744 Find Smallest Letter Greater Than Target
- Error: No resource found that matches the given name (at 'layout_toLeftOf' with value '@id/p
- Find Smallest Letter Greater Than Target(leetcode)
- org.hibernate.HibernateException: More than one row with the given identifier was found: 116, for cl
- ORA-00837: Specified value of MEMORY_TARGET greater than MEMORY_MAX_TARGET
- Print all Jumping Numbers smaller than or equal to a given value
- ORA-00837: Specified value of MEMORY_TARGET greater than MEMORY_MAX_TARGET