Advertisement
viraco4a

LongestZigZagForward

Apr 5th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 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.  
  41. var finalResult = new int[result];
  42. var index = 1;
  43. for (int i = 0, j = 0; i < numbers.Length; i++)
  44. {
  45. if (Math.Max(matrixZ[i, 0], matrixZ[i, 1]) == index)
  46. {
  47. finalResult[j] = numbers[i];
  48. j++;
  49. index++;
  50. }
  51. }
  52. Console.WriteLine(string.Join(" ", finalResult));
  53. }
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement