Test:买卖股票的最好时机

买卖股票的最好时机

http://www.nowcoder.com/questionTerminal/64b4262d4e6d4f6181cd45446a5821ec

题目描述
假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
示例1
输入
复制
[1,4,2]
返回值
复制
3
示例2
输入
复制
[2,4,1]
返回值
复制
2

import java.util.*;

public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
if(null == prices || prices.length == 0) {
return 0;
}
int temMin = Integer.MAX_VALUE;
int temMax = Integer.MIN_VALUE;
// write code here
for(int i = 0;i<prices.length;i++){
temMin = Math.min(temMin,prices[i]);
temMax = Math.max(temMax,prices[i]-temMin);
}
return temMax;
}
}

全部评论
不愧是来哥,这两个变量定义的很美丽
1 回复 分享
发布于 2021-04-13 20:55

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务