买卖股票的最佳时机
买卖股票的最佳实际
一,题目描述
给定一个数组,它的第i哥哥元素prices[i]表示一直给定股票第i条的价格。选择某一条买进这支股票,并选择某一条卖出股票。设计一个算法来计算你所能获得的最大利润。
实例
输入:[7,1,5,3,6,4]
输出:5
输入:prices = [7,6,4,3,1]
输出:0
二、解题思路
遍历数组,找出价格最低的一天,假设在这天买进股票。维护一个价格最低的天数,然后维护一个最大利润,用当天的价格减去最低价格的那天即可。
三、解题方法
一次遍历,维护两个值即可。
代码实现
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for(int i=0; i<prices.length; i++){
if(prices[i] < minPrice){
minPrice = prices[i];
}
if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}
浙公网安备 33010602011771号