Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace _8Task
- {
- class Program
- {
- static void Main(string[] args)
- {
- //Task 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)?
- Console.WriteLine("Please insert 'N' integer number: ");
- int N = int.Parse(Console.ReadLine());
- int[] numbers = new int[N];
- int[] maxSequenceArray = new int[N];
- Console.WriteLine("Please insert 'N' elements in the array: ");
- for (int i = 0; i < N; i++)
- {
- numbers[i] = int.Parse(Console.ReadLine());
- }
- int sum = 0;
- int maxSum = 0;
- int initialIndex = 0;
- int finalIndex = 0;
- for (int j = 0; j < N; j++)
- {
- for (int i = j; i < N; i++)
- {
- sum += numbers[i];
- if (sum > maxSum)
- {
- maxSum = sum;
- initialIndex = j;
- finalIndex = i;
- }
- }
- sum = 0;
- }
- Console.WriteLine(maxSum);
- for (int i = initialIndex; i <= finalIndex; i++)
- {
- Console.WriteLine(numbers[i]);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment