国产探花免费观看_亚洲丰满少妇自慰呻吟_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;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 江陵县| 乐都县| 宁阳县| 米脂县| 阿坝| 安阳市| 麟游县| 惠水县| 延寿县| 会理县| 新昌县| 黑水县| 陆丰市| 安图县| 东至县| 娄底市| 双峰县| 通山县| 修水县| 电白县| 封丘县| 逊克县| 呼伦贝尔市| 固始县| 蚌埠市| 正宁县| 潢川县| 革吉县| 珠海市| 馆陶县| 冕宁县| 车险| 青州市| 炉霍县| 双柏县| 香河县| 福清市| 清涧县| 阳曲县| 长泰县| 平武县|