Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Welcome to Facebook!
- // This is just a simple shared plaintext pad, with no execution capabilities.
- // When you know what language you'd like to use for your interview,
- // simply choose it from the dropdown in the top bar.
- // Enjoy your interview!
- // I'm here
- ///////////////////////////////////////////
- # Question
- Given a sequence of positive integers seq and an integer total, return whether a contiguous sequence of seq sums up to total.
- Examples:
- [1, 2, 3], 4 # False
- [1, 2, 3], 5 # True (because 2 + 3 = 5)
- [1, 2, 3], 6 # True (because 1 + 2 + 3 = 6)
- ////////////////////////////////////////////
- [1,0,3] 0
- // f[i] = sum(sub(i, end))
- // sum(sub(a,b)) = f(b) - f(a)
- public boolean isContiguousSum(int[] seq, int sum) {
- if(seq==null) return false;
- for(int i=0; i<seq.length-1; i++){
- int s = 0;
- for(int j=i; j<seq.length-1; j++){
- s += seq[j];
- if (s == sum) return true;
- }
- }
- return false;
- }
- public boolean isContiguousSum(int[] seq, int sum) {
- if(seq==null) return false;
- int lo=0,hi=1;
- int part = seq[lo];
- while(hi<seq.length-1){
- if(part == sum) return true;
- if(part>sum) {
- part -= seq[lo];
- lo++;
- } else {
- hi++;
- part += seq[hi];
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment