您的位置:首页 > 产品设计 > UI/UE

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: