Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //08. 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}
- using System;
- namespace Sequence_Of_Maximal_Sum
- {
- class Sequence_Of_Maximal_Sum
- {
- static void Main()
- {
- Console.Write("n = ");
- int n = int.Parse(Console.ReadLine());
- int[] arr = new int[n];
- Console.WriteLine("Enter the elements: ");
- for (int i = 0; i < n; i++)
- {
- arr[i] = int.Parse(Console.ReadLine());
- }
- //For testing:
- //int[] arr = { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 };
- int maxSum = 0;
- int sum = 0;
- int startedPos = 0;
- int endedPos = 0;
- for (int i = 0; i < arr.Length; i++)
- {
- for (int j = i + 1; j < arr.Length; j++)
- {
- for (int k = i; k <= j; k++)
- {
- sum += arr[k];
- }
- if (sum > maxSum)
- {
- maxSum = sum;
- startedPos = i;
- endedPos = j;
- }
- sum = 0;
- }
- }
- Console.WriteLine("The sequence with maximal sum is:");
- for (int i = startedPos; i <= endedPos; i++)
- {
- Console.Write("{0} ", arr[i]);
- }
- Console.WriteLine();
- Console.WriteLine("And its sum is {0}", maxSum);
- //==========================================================================================================
- //The Kadane's way with one loop:
- //int sum = arr[0], maxSum = arr[0];
- //int begin = 0;
- //int begin_temp = 0;
- //int end = 0;
- //for (int i = 1; i < arr.Length; i++)
- //{
- // if (maxSum < 0)
- // {
- // maxSum = arr[i];
- // begin_temp = i;
- // }
- // else
- // {
- // maxSum += arr[i];
- // }
- // if (maxSum >= sum)
- // {
- // sum = maxSum;
- // begin = begin_temp;
- // end = i;
- // }
- //}
- //Console.WriteLine("The maximal sum in sequence is {0}\nAnd its sequence is:", maxSum);
- //for (int i = begin; i <= end; i++)
- //{
- // Console.Write("{0} ", arr[i]);
- //}
- //Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement