Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Write a program that finds the maximal increasing sequence in an array.
- //Example: {3, 2, 3, 4, 2, 2, 4} -> {2, 3, 4}.
- using System;
- using System.Collections.Generic;
- class MaximalIncreasingSequence
- {
- static void Main()
- {
- int arrayLength;
- int currentLength = 1;
- int maxLength = 0;
- List<int> indices = new List<int>();
- Console.Write("Enter the array's length: ");
- while (!int.TryParse(Console.ReadLine(), out arrayLength) || arrayLength <= 0)
- {
- Console.Write("Invalid input. Enter a positive integer number: ");
- }
- int[] array = new int[arrayLength];
- for (int i = 0; i < arrayLength; i++)
- {
- Console.Write("Enter the {0} element of the array: ", i);
- while (!int.TryParse(Console.ReadLine(), out array[i]))
- {
- Console.Write("Invalid input. Enter an integer number: ");
- }
- }
- int pointer = array[0];
- for (int i = 1; i < arrayLength; i++)
- {
- if (pointer < array[i])
- {
- pointer = array[i];
- currentLength++;
- }
- else
- {
- pointer = array[i];
- if (maxLength < currentLength)
- {
- maxLength = currentLength;
- indices.Clear();
- indices.Add(i - 1);
- }
- else if (maxLength == currentLength)
- {
- indices.Add(i - 1);
- }
- currentLength = 1;
- }
- }
- if (maxLength < currentLength)
- {
- maxLength = currentLength;
- indices.Clear();
- indices.Add(arrayLength - 1);
- }
- else if (maxLength == currentLength)
- {
- indices.Add(arrayLength - 1);
- }
- if (indices.Count == 1)
- {
- Console.Write("There is one maximal increasing sequence: ");
- }
- else
- {
- Console.WriteLine("There are {0} maximal increasing sequences: ", indices.Count);
- }
- for (int i = 0; i < indices.Count; i++)
- {
- int[] maxSequence = new int[maxLength];
- for (int j = maxLength - 1; j >= 0; j--)
- {
- maxSequence[j] = array[indices[i]];
- indices[i]--;
- }
- Console.WriteLine(string.Join(", ", maxSequence));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement