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: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
方法一、注意数组为空的情况啊!
class Solution {
public int maxProfit(int[] prices) {
if (prices.length==0){
return 0;
}
int last_min= prices[0];
int max_interval =0;
for(int i=1;i<prices.length;i++){
if(prices[i]-last_min>max_interval){
max_interval = prices[i]-last_min;
}
if(prices[i]<last_min){
last_min = prices[i];
}
}
return max_interval;
}
}
本文介绍了一种算法,用于计算给定股票价格数组中通过一次买卖交易可以获得的最大利润。算法首先检查数组是否为空,然后初始化最小购买价格和最大利润。遍历数组过程中不断更新这两个变量,最终返回最大利润。

被折叠的 条评论
为什么被折叠?



