Advertisement
viraco4a

LongestZigZagBackward

Apr 5th, 2018
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. namespace LongestZigZagSequence
  5. {
  6. class Program
  7. {
  8. static void Main()
  9. {
  10. var numbers = Console.ReadLine().Split().Select(s => int.Parse(s)).ToArray();
  11. var matrixZ = new int[numbers.Length, 2];
  12.  
  13. for (int i = 0; i < numbers.Length; i++)
  14. {
  15. matrixZ[i, 0] = 1;
  16. matrixZ[i, 1] = 1;
  17. }
  18. int result = 1;
  19. int maxIndex = 0;
  20.  
  21. for (int i = 1; i < numbers.Length; i++)
  22. {
  23. for (int j = 0; j < i; j++)
  24. {
  25. if (numbers[j] < numbers[i] && matrixZ[i, 0] < matrixZ[j, 1] + 1)
  26. {
  27. matrixZ[i, 0] = matrixZ[j, 1] + 1;
  28. }
  29. if (numbers[j] > numbers[i] && matrixZ[i, 1] < matrixZ[j, 0] + 1)
  30. {
  31. matrixZ[i, 1] = matrixZ[j, 0] + 1;
  32. }
  33. }
  34. if (result < Math.Max(matrixZ[i, 0], matrixZ[i, 1]))
  35. {
  36. result = Math.Max(matrixZ[i, 0], matrixZ[i, 1]);
  37. maxIndex = i;
  38. }
  39. }
  40. var finalResult = new int[result];
  41. var index = maxIndex;
  42. for (int i = numbers.Length - 1, j = result - 1; i >= 0; i--)
  43. {
  44. if (Math.Max(matrixZ[i, 0], matrixZ[i, 1]) == result)
  45. {
  46. finalResult[j] = numbers[i];
  47. j--;
  48. index--;
  49. result--;
  50. }
  51. }
  52. Console.WriteLine(string.Join(" ", finalResult));
  53. }
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement