After a recent interview with a company, I was asked two questions about algorithms:
1. Maximum child segment sum (a classic Dynamic Programming Algorithm)
2. If the data type stack is known, implement the queue.
The Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace ConsoleApplication2
{
Class Program
{
Static void Main (string [] args)
{
Int [] a = new int [] {-1, 3,-5, 1, 8,-7, 8,-5, 6,-5,-6 };
Console. WriteLine ("maximum sub-segment and is:" + MaxSum ());
Queue q = new Queue ();
For (int I = 0; I <10; I ++) q. Push (I );
For (int I = 0; I <11; I ++) Console. WriteLine (q. Pop ());
For (int I = 0; I <10; I ++) q. Push (I );
For (int I = 0; I <11; I ++) Console. WriteLine (q. Pop ());
}
/// <Summary>
/// Maximum child segment and
/// </Summary>
/// <Param name = "array"> </param>
/// <Returns> </returns>
Static int MaxSum (int [] array)
{
Int B = 0;
Int sum = 0;
For (int I = 0; I <array. Length; I ++)
{
If (B> 0) B + = array [I];
Else B = array [I];
If (sum <B) sum = B;
}
Return sum;
}
}
/// <Summary>
/// Custom queue
/// </Summary>
Class Queue
{
Stack <int> sa = new Stack <int> ();
Stack <int> sb = new Stack <int> ();
/// <Summary>
/// Insert elements into the queue
/// </Summary>
/// <Param name = "item"> </param>
Public void Push (int item)
{
Sa. Push (item );
}
/// <Summary>
/// Delete from the queue and return an element
/// </Summary>
/// <Returns> </returns>
Public int? Pop ()
{
If (IsEmpty () return null;
If (sb. Count = 0)
{
While (sa. Count> 0) sb. Push (sa. Pop ());
Return sb. Pop ();
}
Else return sb. Pop ();
}
/// <Summary>
/// Determine whether the queue is empty
/// </Summary>
/// <Returns> </returns>
Public bool IsEmpty ()
{
If (sa. Count = 0 & sb. Count = 0) return true;
Else return false;
}
}
}