aiaiask.com©

开花即结果 提问即答案

用java写一个算法:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
原始问题:

用java写一个算法:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

可以使用动态规划的方法来解决这个问题。假设股票价格数组为prices,长度为n。

首先定义两个变量:minPrice表示当前遍历到的最低股票价格,maxProfit表示当前遍历到的最大利润。

然后遍历整个股票价格数组,对于每个价格,更新minPrice为当前价格和minPrice中的较小值,更新maxProfit为当前价格与minPrice的差值和maxProfit中的较大值。

最后返回maxProfit即为买卖该股票一次可能获得的最大利润。

以下是Java代码实现:

public int maxProfit(int[] prices) {
    int n = prices.length;
    if (n == 0) {
        return 0;
    }
    
    int minPrice = prices[0];
    int maxProfit = 0;
    
    for (int i = 1; i < n; i++) {
        minPrice = Math.min(minPrice, prices[i]);
        maxProfit = Math.max(maxProfit, prices[i] - minPrice);
    }
    
    return maxProfit;
}

这个算法的时间复杂度是O(n),其中n是股票价格数组的长度。

用java写一个算法:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
https://www.aiaiask.com/ask/44335.html
AI / 模型Siliconflow
时间 / DATEAugust 11, 2023, 10:05 PM
语言zh-CN
IP / 区域黑龙江 哈尔滨