Smallest subarray with sum greater than a given value

504 篇文章 0 订阅
// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值