Skip to content

Instantly share code, notes, and snippets.

@AnwarShahriar
Last active January 29, 2018 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnwarShahriar/f49e956ce19ea38071e851b17587527e to your computer and use it in GitHub Desktop.
Save AnwarShahriar/f49e956ce19ea38071e851b17587527e to your computer and use it in GitHub Desktop.
A solution to numrange problem. Problem description and sample input is given with the solution.
/**
Given an array of non negative integers A, and a range (B, C),
find the number of continuous subsequences in the array which have sum S in the range [B, C] or B <= S <= C
Continuous subsequence is defined as all the numbers A[i], A[i + 1], .... A[j]
where 0 <= i <= j < size(A)
Input Description:
First line contains the number of inputs preceding with total number of input
Second line contains B lower range of sum (inclusive)
Third line contains C upper range of sum (inclusive)
Note: The answer is guranteed to fit in a 32 bit signed integer. Following solution doesn't show the technique to read the input.
It assumes inputs are given to the numRange function.
Example:
Input:
5 10 5 1 0 2
6
8
Output:
3
> as [5, 1], [5, 1, 0], [5, 1, 0, 2] are the only 3 continuous subsequence with their sum in the range [6, 8]
==========
Input:
5 80 97 78 45 23
99
269
Output:
7
==========
Input:
1 1
0
0
Output:
0
**/
========================================================================================================================
import java.util.*;
public class NumRange {
public int numRange(ArrayList<Integer> A, int B, int C) {
int i = 0, j = 0, freeze = 0, count = 0;
int len = A.size();
boolean incJ = false;
while (i < len) {
int sum = getSumInRange(A, j, i);
if (!incJ) {
if (sum >= B && sum <= C) {
count++;
freeze = j;
j++;
incJ = true;
} else if (sum > C) {
j++;
if (j > i) {
i++;
}
} else {
i++;
}
} else {
if (sum < B) {
j = freeze;
i++;
incJ = false;
} else {
count++;
j++;
}
}
}
return count;
}
private int getSumInRange(ArrayList<Integer> A, int sIdx, int eIdx) {
int sum = 0;
if (sIdx == eIdx) {
return A.get(sIdx);
}
for (int i = sIdx; i <= eIdx; i++) {
sum += A.get(i);
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment