Description

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [,,,,,]
Output:
Explanation: Buy on day (price = ) and sell on day (price = ), profit = - = .
Not - = , as selling price needs to be larger than buying price.

Example 2:

Input: [,,,,]
Output:
Explanation: In this case, no transaction is done, i.e. max profit = .

题目描述: 给一个数组,每一个元素都代表当前索引的价格。你只有一次买进和卖出的机会,计算买进最低点和卖出最高点。并返回最大差价

思路:首先判断当前点是否可以是买进点。及当前点是否比下一点小。

2,在当前点是买进点的时候,从当前点向尾部遍历,判断当前最大差价点。

3,不断进行比较,找到整体的出现最大差价时的买进点和卖出点

代码如下:

public int MaxProfit(int[] prices)
{
int inIndex = -, outIndex = -;//买进点, 卖出点
int subMax = int.MinValue;//存储最大差价
for (int i = ; i < prices.Length -; i++)
{
if(prices[i] < prices[i + ])//如果当前值比下一个值小,说明此时买进可以有盈利
{
int tempMax = ;
int maxIndex = -;
for (int j = i; j < prices.Length; j++)//从买进处遍历,判断最大差价点的索引
{
int temp = prices[j] - prices[i];
if(temp > tempMax)
{
tempMax = temp;
maxIndex = j;
}
}
if(tempMax > subMax)//更新买进点、卖出点
{
subMax = tempMax;
inIndex = i;
outIndex = maxIndex;
}
}
}
return subMax > ? prices[outIndex] - prices[inIndex] : ; }

最新文章

  1. 工具武装的前端开发工程师 Mac 软件清单
  2. opencv3.0+VS2015+64位win7配置
  3. oracle数据库优化
  4. BOM(浏览器对象模型)的一些内置对象总结
  5. Java的多线程(上)
  6. HDU 4814 Golden Radio Base 模拟
  7. [BZOJ3506] [Cqoi2014] 排序机械臂 (splay)
  8. ●BZOJ 2154 Crash的数字表格
  9. PHP中的Define和Const区别
  10. HTML&amp;javaSkcript&amp;CSS&amp;jQuery&amp;ajax(五)
  11. 廖雪峰Java3异常处理-1错误处理-3抛出异常
  12. Apache poi 使用经验分享
  13. em和px比较
  14. vijos 1659 河蟹王国 线段树区间加、区间查询最大值
  15. (15)如何使用Cocos2d-x 3.0制作基于tilemap的游戏:第三部分(完)
  16. leetcode7_C++整数反转
  17. cmake处理多源文件目录的方法
  18. Hadoop生态圈介绍及入门(转)
  19. Python:格式化操作符(%)
  20. php 开发 错误汇总

热门文章

  1. qt 如何使用 lamda 表达式接收线程中发射的数据,并在里面更新 UI ?
  2. Using-JSONNET-for-dynamic-JSON-parsing
  3. mySQL的表连接
  4. Python基础篇(初始函数)
  5. springcloud费话之Eureka基础
  6. net core微服务构建方案
  7. 转:KVM 虚拟机的克隆
  8. 转帖 java使用poi.3.10读取excel 2010
  9. Windows最值得安装的小众软件
  10. 外部表及oracle数据库内存