Guest User

Untitled

a guest
Jul 25th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. // Welcome to Facebook!
  2.  
  3. // This is just a simple shared plaintext pad, with no execution capabilities.
  4.  
  5. // When you know what language you'd like to use for your interview,
  6. // simply choose it from the dropdown in the top bar.
  7.  
  8. // Enjoy your interview!
  9.  
  10. // I'm here
  11. ///////////////////////////////////////////
  12.  
  13. # Question
  14. Given a sequence of positive integers seq and an integer total, return whether a contiguous sequence of seq sums up to total.
  15. Examples:
  16. [1, 2, 3], 4 # False
  17. [1, 2, 3], 5 # True (because 2 + 3 = 5)
  18. [1, 2, 3], 6 # True (because 1 + 2 + 3 = 6)
  19.  
  20. ////////////////////////////////////////////
  21.  
  22.   [1,0,3] 0
  23.  
  24.  
  25.   // f[i] = sum(sub(i, end))
  26.   // sum(sub(a,b)) = f(b) - f(a)
  27.  
  28. public boolean isContiguousSum(int[] seq, int sum) {
  29.   if(seq==null) return false;
  30.  
  31.  
  32.   for(int i=0; i<seq.length-1; i++){
  33.     int s = 0;
  34.     for(int j=i; j<seq.length-1; j++){
  35.       s += seq[j];
  36.       if (s == sum) return true;
  37.     }
  38.   }
  39.   return false;
  40. }
  41.  
  42.  
  43.  
  44. public boolean isContiguousSum(int[] seq, int sum) {
  45.   if(seq==null) return false;
  46.  
  47.   int lo=0,hi=1;
  48.  
  49.   int part = seq[lo];
  50.  
  51.   while(hi<seq.length-1){
  52.     if(part == sum) return true;
  53.     if(part>sum) {
  54.       part -= seq[lo];
  55.       lo++;
  56.     } else {
  57.       hi++;
  58.       part += seq[hi];
  59.     }
  60.   }
  61.  
  62.   return false;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment