Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*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)?*/
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- //We enter the size of the array
- Console.WriteLine("Enter the size of the array:");
- int size = int.Parse(Console.ReadLine());
- int[] arr = new int[size];
- //We are entering the value of each element of the array
- for (int i = 0; i < arr.Length; i++)
- {
- Console.Write("arr[{0}] = ", i);
- arr[i] = int.Parse(Console.ReadLine());
- }
- //Extracting the maximal sequence
- int j = 0;
- int firstElem = 0;
- int numElems = 0;
- int sum = 0;
- int maxSum = 0;
- while (j < arr.Length)
- {
- for (int i = j; i < arr.Length; i++)
- {
- sum += arr[i];
- if (sum > maxSum)
- {
- maxSum = sum;
- firstElem = j;
- numElems = i - firstElem + 1;
- }
- }
- j++;
- sum = 0;
- }
- //Simply printing in the desired way
- for (int k = 0; k < arr.Length - 1; k++)
- {
- Console.Write("{0}", arr[k]);
- if (k != arr.Length - 2)
- {
- Console.Write(", ");
- }
- }
- Console.Write(" ----> ");
- for (int a = firstElem; a < numElems + firstElem; a++)
- {
- Console.Write("{0}", arr[a]);
- if (a != numElems + firstElem - 1)
- {
- Console.Write(", ");
- }
- }
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement