Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. //To find the length of longest zig-zag subsequence
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. // function to return max of two numbers
  6. int max(int a, int b) { return (a > b) ? a : b; }
  7.  
  8. // Function to return longest Zig-Zag subsequence length
  9. int zzis(int arr[], int n)
  10. {
  11. /*Z[i][0] = Length of the longest Zig-Zag subsequence
  12. ending at index i and last element is greater
  13. than its previous element
  14. Z[i][1] = Length of the longest Zig-Zag subsequence
  15. ending at index i and last element is smaller
  16. than its previous element */
  17. int Z[n][2];
  18.  
  19. /* Initialize all values from 1 */
  20. for (int i = 0; i < n; i++)
  21. Z[i][0] = Z[i][1] = 1;
  22.  
  23. int res = 1; // Initialize result
  24.  
  25. /* Compute values in bottom up manner */
  26. for (int i = 1; i < n; i++)
  27. {
  28. // Consider all elements as previous of arr[i]
  29. for (int j = 0; j < i; j++)
  30. {
  31. // If arr[i] is greater, then check with Z[j][1]
  32. if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1)
  33. Z[i][0] = Z[j][1] + 1;
  34.  
  35. // If arr[i] is smaller, then check with Z[j][0]
  36. if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1)
  37. Z[i][1] = Z[j][0] + 1;
  38. }
  39.  
  40. /* Pick maximum of both values at index i */
  41. if (res < max(Z[i][0], Z[i][1]))
  42. res = max(Z[i][0], Z[i][1]);
  43. }
  44.  
  45. return res;
  46. }
  47.  
  48. /* Driver program */
  49. int main()
  50. {
  51. int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 };
  52. int n = sizeof(arr)/sizeof(arr[0]);
  53. printf("Length of Longest Zig-Zag subsequence is %d\n",
  54. zzis(arr, n) );
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement