andreykata

Ex08SequenceMaxSum

Jul 5th, 2013
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1.  
  2. // Write a program that finds the sequence of maximal sum in given array. Example:
  3. // {2, 3, -6, -1, 2, -1, 6, 4, -8, 8}  {2, -1, 6, 4}
  4.  
  5. using System;
  6.  
  7. class Ex08SequenceMaxSum
  8. {
  9. static void Main(string[] args)
  10. {
  11.  
  12. int[] arr = { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 };
  13. int maxSum = 0;
  14. int currentSum = 0;
  15. int startIndex = 0;
  16. int endIndex = 1;
  17. for (int i = 0, j = 0; i < arr.Length; i++)
  18. {
  19. if (arr[j] <= 0)
  20. j++;
  21. else if (currentSum + arr[i] > maxSum)
  22. {
  23. currentSum += arr[i];
  24. maxSum = currentSum;
  25. startIndex = j;
  26. endIndex = i;
  27. }
  28. else if ((i < arr.Length - 1) && (arr[i] + arr[i + 1] > 0))
  29. currentSum += arr[i];
  30. else
  31. {
  32. currentSum = 0;
  33. i = j;
  34. j++;
  35. }
  36. }
  37.  
  38. Console.WriteLine(maxSum);
  39. for (int i = startIndex; i <= endIndex; i++)
  40. {
  41. Console.Write(arr[i] + " ");
  42. }
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment