最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
来源:互联网 发布:个人收支软件免费 编辑:程序博客网 时间:2024/04/26 23:40
LeetCode
我们有一个股票的数组,数组是每时间的钱,我们只能买入一次和卖出一次,求我们的最大收益。
我们知道了一个数组,那么我们可以在低价买入,然后高价卖出,但是需要知道我们的低价需要在高价之前。
我们可以两个变量,一个记录最低价,一个记录我们卖出得到最大钱。
public static int MaxProfit(int[] price) { if (price.Length <= 1) { return 0; } int minPrice = price[0];//最小的钱 int maxProfit = 0;//收益 for (int i = 1; i < price.Length; i++) { minPrice = Math.Min(minPrice, price[i]); int currentProfit = price[i] - minPrice; maxProfit = Math.Max(maxProfit, currentProfit); } return maxProfit; }
我们不断计算当前最小和当前价格的卖出得到的钱,如果大于我们的最大卖出钱就记下,这样就得到我们的最大卖出钱。
我们来个测试,UWP的测试其实和我发的单元测试是一样。
新建测试,然后写一个类
[TestClass] public class BestTimetoBuyandSellStock { [TestMethod] public void MaxProfit() { int[] price = new[] { 2,3,2,5 }; var temp = Algorithm.Model.BestTimetoBuyandSellStock.MaxProfit(price); Assert.AreEqual(temp, 3); price = new[] { 5, 15, 1, 3, 6, 5, 3, 2, 5, 6, 7, 2, 2, 3 }; temp = Algorithm.Model.BestTimetoBuyandSellStock.MaxProfit(price); Assert.AreEqual(temp, 10); } }
代码:https://github.com/lindexi/Algorithm/blob/master/Algorithm/Model/BestTimetoBuyandSellStock.cs
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系。
3 0
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- Best Time to Buy and Sell Stock 最佳时间买入卖出股票(一次买入卖出) @LeetCode
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode-121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)
- LeetCode OJ 之 Best Time to Buy and Sell Stock II (买卖股票的最佳时间 2)
- LeetCode OJ 之 Best Time to Buy and Sell Stock III (买卖股票的最佳时间 - 三)
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- Best Time to Buy and Sell Stock 【最佳买卖股票的时间】【容易】
- 123/188/309.Best Time to Buy and Sell Stock 买股票的最佳时间
- 121. Best Time to Buy and Sell Stock 最佳买卖股票时间
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- PRM详解
- UIScrollView图片循环轮播
- 安卓学习笔记之———五大布局
- 异常小结
- C语言关键字之volatile的使用
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- Unity+Vuforia SDKAR开发系列教程--2.2 Vuforia sdk for unity
- Android开发常用工具类之图像处理
- HihoCoder]#1375 : 沙漠之旅
- 使用caffe中的imagenet对自己的图片进行分类训练(超级详细版)
- 容器继承关系
- Android XML布局与View之间的转换
- java中的“属性”:property、attribute、parameter
- 编译器