Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * 8. 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 SequenceOfMaximalSum
- {
- static void Main()
- {
- int[] arr = { 3, 2, 7, 4, 5, 18, 4, 54, 32 };
- int maxTemp = int.MinValue;
- int maxEnd = 0;
- int start = 0;
- int startTemp = 0;
- int end = 0;
- for (int i = 0; i < arr.Length; i++)
- {
- maxEnd += arr[i];
- if (arr[i] > maxEnd)
- {
- maxEnd = arr[i];
- startTemp = i;
- }
- if (maxEnd > maxTemp)
- {
- maxTemp = maxEnd;
- start = startTemp;
- end = i;
- }
- }
- Console.WriteLine("Maximal sum is: {0}", maxTemp);
- for (int j = start; j <= end; j++)
- {
- Console.Write(arr[j] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement