【LintCode】买卖股票的最佳时机
2017-06-11 08:44
295 查看
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例
给出一个数组样例 [3,2,3,1,2], 返回 1
思路:简单贪心问题,注意处理边界问题
代码如下:public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if(prices.length <= 1)
{
return 0;
}
int ilow = prices[0];
int ians = 0;
for(int i = 1;i < prices.length;i++)
{
if(prices[i] - ilow > ians)
{
ians = prices[i] - ilow;
}
if(prices[i] < ilow)
{
ilow = prices[i];
}
}
return ians;
}
}
样例
给出一个数组样例 [3,2,3,1,2], 返回 1
思路:简单贪心问题,注意处理边界问题
代码如下:public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if(prices.length <= 1)
{
return 0;
}
int ilow = prices[0];
int ians = 0;
for(int i = 1;i < prices.length;i++)
{
if(prices[i] - ilow > ians)
{
ians = prices[i] - ilow;
}
if(prices[i] < ilow)
{
ilow = prices[i];
}
}
return ians;
}
}
相关文章推荐
- Lintcode 150.买卖股票的最佳时机 II
- LintCode_149_买卖股票的最佳时机
- [Lintcode] #150 买卖股票的最佳时机 II
- Lintcode 买卖股票的最佳时机 II
- LintCode 买卖股票的最佳时机I II III IV
- lintcode:买卖股票的最佳时机 I
- LintCode:买卖股票的最佳时机 II
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- 买卖股票的最佳时机 —LintCode
- LintCode 151 买卖股票的最佳时机 III
- lintcode--买卖股票的最佳时机
- 【LintCode】 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II
- lintcode---买卖股票的最佳时机II
- LintCode-买卖股票的最佳时机
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 买卖股票的最佳时机 IV -LintCode
- 买卖股票的最佳时机 III-LintCode
- lintcode:买卖股票的最佳时机 IV
- lintcode:买卖股票的最佳时机 II
- lintcode-150-买卖股票的最佳时机 II