Venciity

[Jumpstart C#] Arrays 06A-TheSumOfANumberOfElements

Feb 18th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.80 KB | None | 0 0
  1. /*  Нека е дадена редица от цели числа.
  2.     Ако със S обозначим сумата на елементите на редица:
  3.     - намерете и отпечатайте подредицата с максимално S.
  4.     Например: { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 } -> { 2, -1, 6, 4 }  
  5.  
  6.     забележка : ако имаме повече от една редица с максимална сума , печатаме само първата  */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12.  
  13. namespace _06A_TheSumOfANumberOfElements
  14. {
  15.     class TheSumOfANumberOfElements
  16.     {
  17.         static void Main()
  18.         {
  19.             Console.Write("Numbers of array = ");
  20.             int n = Int32.Parse(Console.ReadLine());
  21.             int[] array = new int[n];
  22.             for (int i = 0; i < n; i++)
  23.             {
  24.                 Console.Write("Element {0} = ", i + 1);
  25.                 array[i] = Int32.Parse(Console.ReadLine());
  26.             }
  27.  
  28.             int arrayLen = array.Length;
  29.  
  30.             int maxSum = Int32.MinValue;
  31.             int startPos = 0;
  32.             int endPos = 0;
  33.  
  34.             for (int i = 0; i < arrayLen; i++)
  35.             {
  36.                 int sum = 0;
  37.  
  38.                 for (int j = i; j < arrayLen; j++)
  39.                 {
  40.                     sum += array[j];
  41.  
  42.                     if (sum > maxSum)
  43.                     {
  44.                         maxSum = sum;
  45.                         startPos = i;
  46.                         endPos = j;
  47.                     }
  48.                 }
  49.             }
  50.  
  51.             for (int i = startPos; i <= endPos; i++)
  52.             {
  53.                 Console.Write(array[i] + " ");
  54.             }
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment