// 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
最新推荐文章于 2024-08-17 12:49:11 发布