leetcode第30题(best-time-to-buy-and-sell-stock)

xiaoxiao2021-02-28  27

题目:

Say you have an array for which the i th element is the price of a given stock on day i. 

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

思路:用一个变量存储当前的最大利润,一个变量继续计算到当天卖出的最大利润。

代码:

public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0){ return 0; } int local = 0; int global = 0; for(int i=0;i<prices.length-1;i++){ local = Math.max(local+prices[i+1]-prices[i],0); global = Math.max(local,global); } return global; } }

转载请注明原文地址: https://www.6miu.com/read-2250097.html

最新回复(0)