ellapt

T7.8.MaxSumSequence

Jan 15th, 2013
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. using System;
  2.  
  3. class MaxSumSequence
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. uint n;
  9. Console.WriteLine("Find the sequence of maximal sum in given array");
  10. do
  11. {
  12. Console.Write("Enter array length: ");
  13. }
  14. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  15.  
  16. int[] arrayOfints = new int[n];
  17.  
  18. Console.WriteLine("Enter the elements of the array (please, enter at least one positive number):");
  19. for (int i = 0; i < n; i++)
  20. {
  21. arrayOfints[i] = int.Parse(Console.ReadLine());
  22. }
  23.  
  24. int previousMax = arrayOfints[0];
  25. int endMax = arrayOfints[0];
  26. int start = 0;
  27. int tempStart = 0;
  28. int end = 0;
  29.  
  30. for(int i = 1; i < n; i++)
  31. {
  32. endMax+=arrayOfints[i];
  33. if(arrayOfints[i] > endMax)
  34. {
  35. endMax = arrayOfints[i];
  36. tempStart = i;
  37. }
  38.  
  39. if(endMax > previousMax )
  40. {
  41. previousMax = endMax;
  42. start = tempStart;
  43. end = i;
  44. }
  45. }
  46. Console.WriteLine("The maximal sum sequence starts from index {0} and ends with index {1}:",start,end);
  47. endMax = 0;
  48. for (int i = start; i <= end; i++)
  49. {
  50. endMax += arrayOfints[i];
  51. Console.WriteLine(arrayOfints[i]);
  52. }
  53. Console.WriteLine("The sum is: {0}",endMax);
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment