Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //Write a program that finds the sequence of maximal sum in given array. Example:
- // {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} => {2, -1, 6, 4}
- // Can you do it with only one loop (with single scan through the elements of the array)?
- class Program
- {
- static void Main(string[] args)
- {
- int[] array = { -1, 3, -5, 4, 6, -1, 2, -7, 13, -3 };
- //For any given array you can delete the previous line uncooment the next comment and enter the elements of the array manually.
- //int[] array = new int[N];
- //int N = int.Parse(Console.ReadLine());
- //for (int i = 0; i < array.Length; i++)
- //{
- // array[i] = int.Parse(Console.ReadLine());
- //}
- int sum = 0;
- int maxSum = 0;
- int firstIndex=0;
- int lastIndex=0;
- for (int i = 0; i < array.Length; i++)
- {
- sum+=array[i];
- if (sum > 0&&sum>maxSum)
- {
- maxSum = sum;
- lastIndex = i;
- }
- else if (sum<0)
- {
- sum = 0;
- lastIndex = 0;
- firstIndex=i+1;
- }
- }
- Console.WriteLine("{0}, {1}, {2}", maxSum, firstIndex, lastIndex);
- for (int i = firstIndex; i <= lastIndex; i++)
- {
- Console.Write("{0}, ",array[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement