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)?
- */
- namespace _08_01_SequenceWithMaxSum
- {
- using System;
- class SequenceWithMaxSum
- {
- static void Main()
- {
- Console.WriteLine("Please, insert the length of the array:");
- int n = int.Parse(Console.ReadLine());
- Console.WriteLine("Please, insert the elements of the array:");
- int[] array = new int[n];
- for (int i = 0; i < n; i++)
- {
- array[i] = int.Parse(Console.ReadLine());
- }
- int maxSum = 0;
- int currentSum = 0;
- int startPosition = 0;
- for (int i = 0; i < n; i++)
- {
- for (int j = i; j < n; j++)
- {
- currentSum += array[j];
- }
- if (currentSum > maxSum)
- {
- maxSum = currentSum;
- startPosition = i;
- }
- currentSum = 0;
- }
- Console.WriteLine("The max sum of consecutive elements = {0}", maxSum);
- Console.WriteLine("The consecutive elements with max sum are:");
- currentSum = 0;
- while (currentSum < maxSum)
- {
- Console.WriteLine(array[startPosition]);
- currentSum += array[startPosition];
- startPosition++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement