Guest User

Untitled

a guest
Jun 13th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. int test(int* arr, int len, int k) {
  2. int minIndex = 0;
  3. int maxIndex = 0;
  4. int start = 0;
  5. int end = 0;
  6. int maxLength = 0;
  7. for (int i = 1; i < len; i++) {
  8. end = i;
  9. // Update the minimum and maximum if necessary while scanning the array
  10. if (arr[i] < arr[minIndex])
  11. minIndex = i;
  12. if (arr[i] > arr[maxIndex])
  13. maxIndex = i;
  14. // Check the new maximum/minimum doesn't make the subarray invalid
  15. if (arr[maxIndex] - arr[minIndex] > k) {
  16. // We broke the subarray, check the length of the longest subarray until now
  17. if (end - start > maxLength)
  18. maxLength = end - start;
  19.  
  20. // Restart from the second element, then the third, and so on
  21. start++;
  22. maxIndex = minIndex = start;
  23. i = start;
  24. }
  25. }
  26.  
  27. return maxLength;
  28. }
Add Comment
Please, Sign In to add comment