Skip to content

Commit ee1339a

Browse files
committed
best time to buy and sell stock
1 parent 77ffda8 commit ee1339a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* ==============================================================================
2+
* 功能描述:ThirdMaximumNumber
3+
* 创 建 者:gz
4+
* 创建日期:2017/5/1 8:25:57
5+
* ==============================================================================*/
6+
using System;
7+
using System.Collections.Generic;
8+
using System.Linq;
9+
using System.Text;
10+
// Say you have an array for which the ith element is the price of a given stock on day i.
11+
12+
// If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
13+
14+
// Example 1:
15+
// Input: [7, 1, 5, 3, 6, 4]
16+
// Output: 5
17+
18+
// max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
19+
// Example 2:
20+
// Input: [7, 6, 4, 3, 1]
21+
// Output: 0
22+
23+
// In this case, no transaction is done, i.e. max profit = 0.
24+
namespace Array.Lib
25+
{
26+
/// <summary>
27+
/// 121. Best Time to Buy and Sell Stock
28+
/// </summary>
29+
public class BuyAndSellSln
30+
{
31+
public int MaxProfit(int[] prices)
32+
{
33+
int premax = 0;
34+
int curmax = 0;
35+
for(int i=1; i<prices.Length; i++)
36+
{
37+
int cal = prices[i]-prices[i-1];
38+
curmax = Math.Max(cal,cal+curmax);
39+
premax = Math.Max(curmax,premax);
40+
}
41+
return premax;
42+
}
43+
44+
}
45+
}

0 commit comments

Comments
 (0)