Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Task_8_SequenceMaxSum
- {
- class Program
- {
- static void Main()
- {
- int[] Arr = new int[10];
- string input;
- int CurrentSum = 0;
- int MaxSum = 0;
- int MaxSeqLenght = 0;
- int EndPosition = 0;
- int EndPositionMax = 0;
- for (int i = 0; i < Arr.Length; i++)
- {
- Console.Write("Please enter element {0} of the array: ", i);
- input = Console.ReadLine();
- while (int.TryParse(input, out Arr[i]) == false)
- {
- Console.Write("Please enter a valid integer!: ");
- input = Console.ReadLine();
- }
- }
- for (int CountOfElements = 2; CountOfElements <= Arr.Length; CountOfElements++) //Increase number of elements to sum in every loop
- {
- for (int StartPosition = 0; StartPosition <= Arr.Length - CountOfElements; StartPosition++) //Move the start position in every loop
- {
- for (int i = 0; i < CountOfElements; i++) //Calculate every sum
- {
- CurrentSum += Arr[StartPosition + i];
- EndPosition = StartPosition + i;
- }
- if (CurrentSum > MaxSum) //Check every sum if there is a bigger one
- {
- MaxSum = CurrentSum;
- MaxSeqLenght = CountOfElements;
- EndPositionMax = EndPosition;
- }
- CurrentSum = 0; //Restart the current sum
- }
- CurrentSum = 0;
- }
- //Now print the elements
- Console.Write("The sequence with max sum is: { ");
- for (int i = EndPositionMax - MaxSeqLenght + 1; i <= EndPositionMax; i++)
- {
- Console.Write(Arr[i] + " ");
- }
- Console.Write("}");
- Console.WriteLine(MaxSeqLenght + " elements");
- Console.WriteLine("Max Sum: " + MaxSum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement