- I was trying to solve Problem 279-B.
Given an natural number,
t, and an array,a[0],...,a[n-1], of natural numbers, find the maximum length of a continuous subarray,a[i],...,a[j]inawherea[i]+...+a[j] <= t. e.g. a=[3,1,2,1] and t=5 -> 3(1,2,1) ; a=[2,2,3] and t=3 -> 1 - I thought of an O(n2) solution.
Double looping to calculate sums and kind of brute force.
- I also thought of maximum sum of a subarray in an array by dynamic programming.
- I saw this solution which is O(n lg n)
By creating a sum array defined as:
sum[i]=sum[i−1]+array[i]// for all i>0.
sum[i]=array[i] // for i=0
Then finding j such that (by binary search)
sum[j]−sum[i]//j>i
- I saw this solution(1) which is similar to this solution to a different problem(2) both of which have an almost same O(n) solution.
Solution 1:
int n; long t; scanf("%d %ld", &n, &t);
long *minutes = new long[n];
long totalTime = 0;
for(int k = 0; k < n; k++){scanf("%ld", minutes + k); totalTime += minutes[k];}
long start(0), finish(0), currentSum(0), output(0);
while(finish < n){
currentSum += minutes[finish++];
while(currentSum > t){currentSum -= minutes[start++];}
if(output < finish - start){output = finish - start;}
}
printf("%ld\n", output);
delete[] minutes;
return 0;
Solution 2:
int curr_sum = arr[0], start = 0, i;
for (i = 1; i <= n; i++)
{
// If curr_sum exceeds the sum, then remove the starting elements
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start++;
}
if (curr_sum == sum)
{
printf ("Sum found between indexes %d and %d", start, i-1);
return 1;
}
if (i < n)
curr_sum = curr_sum + arr[i];
}
printf("No subarray found");
return 0;
Why does the last approach work(Solution 1for sum less than a fixed number and solution 2 for sum equal to a fixed number) I don't seem to get it. I couldn't find the reason or proof for it. I don't know whether it's a named algorithm.