Advertisement
svetoslavhl

Untitled

May 21st, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. /*8 Write a program that finds the sequence of maximal sum in given array.
  2.  
  3. Example: {2, 3, -6, -1,2,-1,6,4,-8,8} -> {2,-1,6,4}
  4.  
  5. Can you do it with only one loop (with single scan through the elements of the array)?*/
  6.  
  7. using System;
  8.  
  9.  
  10.  
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. //We enter the size of the array
  16. Console.WriteLine("Enter the size of the array:");
  17. int size = int.Parse(Console.ReadLine());
  18. int[] arr = new int[size];
  19.  
  20. //We are entering the value of each element of the array
  21.  
  22. for (int i = 0; i < arr.Length; i++)
  23. {
  24.  
  25. Console.Write("arr[{0}] = ", i);
  26. arr[i] = int.Parse(Console.ReadLine());
  27.  
  28.  
  29. }
  30.  
  31.  
  32.  
  33. //Extracting the maximal sequence
  34.  
  35. int j = 0;
  36. int firstElem = 0;
  37. int numElems = 0;
  38. int sum = 0;
  39. int maxSum = 0;
  40.  
  41.  
  42.  
  43. while (j < arr.Length)
  44. {
  45.  
  46.  
  47. for (int i = j; i < arr.Length; i++)
  48. {
  49.  
  50. sum += arr[i];
  51. if (sum > maxSum)
  52. {
  53. maxSum = sum;
  54. firstElem = j;
  55. numElems = i - firstElem + 1;
  56.  
  57. }
  58.  
  59.  
  60.  
  61.  
  62. }
  63.  
  64. j++;
  65. sum = 0;
  66.  
  67. }
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90. //Simply printing in the desired way
  91.  
  92.  
  93. for (int k = 0; k < arr.Length - 1; k++)
  94. {
  95.  
  96. Console.Write("{0}", arr[k]);
  97. if (k != arr.Length - 2)
  98. {
  99. Console.Write(", ");
  100. }
  101.  
  102.  
  103.  
  104.  
  105.  
  106. }
  107.  
  108. Console.Write(" ----> ");
  109.  
  110.  
  111. for (int a = firstElem; a < numElems + firstElem; a++)
  112. {
  113.  
  114.  
  115. Console.Write("{0}", arr[a]);
  116. if (a != numElems + firstElem - 1)
  117. {
  118. Console.Write(", ");
  119. }
  120.  
  121. }
  122.  
  123. Console.WriteLine();
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130. }
  131. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement