Day3. Start Algorithm
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_121._Best_Time_to_Buy_and_Sell_Stock</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
10
121. Best Time to Buy and Sell Stock/Program.cs
Normal file
10
121. Best Time to Buy and Sell Stock/Program.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace _121._Best_Time_to_Buy_and_Sell_Stock
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine(new Solution().MaxProfit(new int[] { 7, 1, 5, 3, 6, 4 }));
|
||||
}
|
||||
}
|
||||
}
|
||||
27
121. Best Time to Buy and Sell Stock/Solution.cs
Normal file
27
121. Best Time to Buy and Sell Stock/Solution.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
namespace _121._Best_Time_to_Buy_and_Sell_Stock;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public int MaxProfit(int[] prices)
|
||||
{
|
||||
int min = prices[0];
|
||||
int max = prices[0];
|
||||
bool hasMax = false;
|
||||
int res = 0;
|
||||
foreach (int price in prices)
|
||||
{
|
||||
if (price > max || hasMax == false)
|
||||
{
|
||||
max = price;
|
||||
hasMax = true;
|
||||
res = Math.Max(max - min, res);
|
||||
}
|
||||
if (price < min)
|
||||
{
|
||||
min = price;
|
||||
hasMax = false;
|
||||
}
|
||||
}
|
||||
return res > 0 ? res : 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user