zornitza_gencheva

Task 8

Jul 7th, 2013
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _8Task
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. //Task 8: Write a program that finds the sequence of maximal sum in given array.
  14. //Example: {2, 3, -6, -1, 2, -1, 6, 4, -8, 8}  {2, -1, 6, 4};
  15. //Can you do it with only one loop (with single scan through the elements of the array)?
  16.  
  17. Console.WriteLine("Please insert 'N' integer number: ");
  18. int N = int.Parse(Console.ReadLine());
  19. int[] numbers = new int[N];
  20. int[] maxSequenceArray = new int[N];
  21.  
  22. Console.WriteLine("Please insert 'N' elements in the array: ");
  23. for (int i = 0; i < N; i++)
  24. {
  25. numbers[i] = int.Parse(Console.ReadLine());
  26. }
  27.  
  28. int sum = 0;
  29. int maxSum = 0;
  30. int initialIndex = 0;
  31. int finalIndex = 0;
  32.  
  33. for (int j = 0; j < N; j++)
  34. {
  35. for (int i = j; i < N; i++)
  36. {
  37. sum += numbers[i];
  38. if (sum > maxSum)
  39. {
  40. maxSum = sum;
  41. initialIndex = j;
  42. finalIndex = i;
  43. }
  44. }
  45.  
  46. sum = 0;
  47. }
  48.  
  49. Console.WriteLine(maxSum);
  50.  
  51. for (int i = initialIndex; i <= finalIndex; i++)
  52. {
  53. Console.WriteLine(numbers[i]);
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment