Advertisement
kskondov

Untitled

Dec 16th, 2013
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System;
  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. //    Can you do it with only one loop (with single scan through the elements of the array)?
  5.  
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.  
  11.             int[] array = { -1, 3, -5, 4, 6, -1, 2, -7, 13, -3 };
  12.             //For any given array you can delete the previous line uncooment the next comment and enter the elements of the array manually.
  13.  
  14.             //int[] array = new int[N];
  15.             //int N = int.Parse(Console.ReadLine());
  16.             //for (int i = 0; i < array.Length; i++)
  17.             //{
  18.             //    array[i] = int.Parse(Console.ReadLine());
  19.             //}
  20.  
  21.             int sum = 0;
  22.             int maxSum = 0;
  23.             int firstIndex=0;
  24.             int lastIndex=0;
  25.             for (int i = 0; i < array.Length; i++)
  26.             {
  27.                 sum+=array[i];
  28.                 if (sum > 0&&sum>maxSum)
  29.                 {
  30.                    
  31.                     maxSum = sum;
  32.                     lastIndex = i;
  33.                 }
  34.                
  35.                 else if (sum<0)
  36.                 {
  37.                     sum = 0;
  38.                     lastIndex = 0;
  39.                     firstIndex=i+1;
  40.                 }
  41.             }
  42.             Console.WriteLine("{0}, {1}, {2}", maxSum, firstIndex, lastIndex);
  43.             for (int i = firstIndex; i <= lastIndex; i++)
  44.             {
  45.                 Console.Write("{0}, ",array[i]);
  46.             }
  47.  
  48.         }
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement