-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum_size_subarray_sum.cpp
88 lines (77 loc) · 2.39 KB
/
minimum_size_subarray_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// https://leetcode.com/problems/minimum-size-subarray-sum/
// June 17, 2016
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums)
{
if (nums.empty())
{
return 0; // 0 represents failure to find the required subarray having sum >= s
}
// initialize subarray sum
int subarray_sum = nums[0];
int min_subarray_len;
// Notation: subarray_sum is the sum of sub-array till nums[i]
// case (a): min_subarray_len is undefined. sum of nums[0,...,i] < s
// case (b): Its sum of nums[i-min_subarray_len+1,....,i] i.e. sum of sub-array of
// length min_subarray_len ending at nums[i]
bool flag_subarray_found = (subarray_sum < s) ? false : true;
if (flag_subarray_found)
{
min_subarray_len = 1;
}
for (int i=1; i != nums.size(); ++i)
{
if (!flag_subarray_found)
{
subarray_sum += nums[i];
if (subarray_sum >= s)
{
flag_subarray_found = true;
min_subarray_len = i+1;
}
}
else
{
subarray_sum += (nums[i] - nums[i-min_subarray_len]);
}
if (flag_subarray_found)
{
// Check if we can have a smaller sub array with sum >= s
while ( (min_subarray_len > 1) && ((subarray_sum - nums[i-(min_subarray_len-1)]) >= s) )
{
subarray_sum -= nums[i-(min_subarray_len-1)];
--min_subarray_len;
}
if (min_subarray_len == 1)
{
break; // No need to check further as there can't be a smaller sub-array satisfying the condition sum >= s
}
}
}
if (flag_subarray_found)
{
return min_subarray_len;
}
else
{
return 0;
}
}
};
int main(int argc, char* argv[])
{
int s = 6;
vector<int> nums = {10,2,3};
Solution sln;
int minSubArrayLen = sln.minSubArrayLen(s, nums);
cout << "min sub array length: " << minSubArrayLen << endl;
return 0;
}
/**
* Space complexity: O(1)
* Time complexity: O(n)
*/