星空网 > 软件开发 > Java

[LeetCode] Best Time to Buy and Sell Stock

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

     这道题就不仅仅只是算法题了,我们还要考虑到生活中的常识。

     比如这个是Buy and Sell,就说明我们必须是先Buy然后再Sell。

     比如第五天价格最低,第三天价格最高,我们肯定不能第五天买了然后穿越回去第三天卖出去啊。所以loop的时候要考虑到这些因素。

     代码如下。~

public class Solution {  public int maxProfit(int[] prices) {    //special case    if(prices==null||prices.length<2){      return 0;    }    int min=prices[0];    int profit=0;    for(int i=0;i<prices.length;i++){      if(profit<(prices[i]-min)){        profit=prices[i]-min;      }else if(prices[i]<min){        min=prices[i];      }    }    return profit;  }}

 




原标题:[LeetCode] Best Time to Buy and Sell Stock

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

如何降低谷歌广告CPC:https://www.kjdsnews.com/a/1452322.html
DTC品牌出海策略全面解析_DTC品牌在出海时代如何破解获客困局及相关策略和解决方案:https://www.kjdsnews.com/a/1452323.html
外贸独立站建站服务器选择:香港服务器VS美国服务器:https://www.kjdsnews.com/a/1452324.html
TikTok跨境电商:做跨境要准备什么?前期跨境怎么做?:https://www.kjdsnews.com/a/1452325.html
如何解决中东跨境物流难题?物流怎么选?:https://www.kjdsnews.com/a/1452326.html
如何通过谷歌关键词广告吸引更多B2B询盘:https://www.kjdsnews.com/a/1452327.html
去日本入住酒店,东西随意用却有一个特殊“要:https://www.vstour.cn/a/411241.html
中国有哪些著名的酒店品牌。:https://www.vstour.cn/a/411242.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流