Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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)?
- using System;
- class SequenceOfMaxSum
- {
- static void Main()
- {
- int arrayLength;
- Console.Write("Enter the array's length: ");
- while (!int.TryParse(Console.ReadLine(), out arrayLength) || arrayLength <= 0)
- {
- Console.Write("Invalid input. Enter a positive integer number: ");
- }
- int[] array = new int[arrayLength];
- for (int i = 0; i < arrayLength; i++)
- {
- Console.Write("Enter the {0} element of the array: ", i);
- while (!int.TryParse(Console.ReadLine(), out array[i]))
- {
- Console.Write("Invalid input. Enter an integer number: ");
- }
- }
- int maxSum = array[0];
- int currentSum = array[0];
- int startIndex = 0;
- int endIndex = 0;
- int bestStart = startIndex;
- int bestEnd = endIndex;
- for (int i = 1; i < array.Length; i++)
- {
- if (currentSum > 0)
- {
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- bestStart = startIndex;
- endIndex = i;
- bestEnd = endIndex;
- }
- currentSum += array[i];
- }
- else
- {
- currentSum = array[i];
- startIndex = i;
- endIndex = i;
- }
- }
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- bestStart = startIndex;
- bestEnd = array.Length;
- }
- int[] maxSequence = new int[bestEnd - bestStart];
- for (int i = bestStart, j = 0; i < bestEnd; i++, j++)
- {
- maxSequence[j] = array[i];
- }
- Console.WriteLine("The sequence {0} has maximal sum {1}.", string.Join(", ", maxSequence), maxSum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement