国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Best Time to Buy and Sell Stock

2019-11-15 01:09:31
字體:
來源:轉載
供稿:網友
[LeetCode] Best Time to Buy and Sell Stock

Say you have an array for which theithelement is the PRice of a given stock on dayi.

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;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麟游县| 黎城县| 乌拉特中旗| 雷山县| 元谋县| 阳春市| 蒲江县| 南乐县| 增城市| 昌吉市| 日照市| 临沂市| 镇安县| 四川省| 靖西县| 那坡县| 枣强县| 柯坪县| 阿拉尔市| 黎平县| 驻马店市| 东安县| 兴和县| 三都| 星子县| 汕尾市| 焦作市| 江山市| 五台县| 哈巴河县| 班玛县| 饶平县| 通榆县| 江安县| 沁阳市| 兴山县| 海口市| 肥东县| 灵璧县| 林西县| 宿迁市|