121.Best Time to Buy and Sell Stock

来源:互联网 发布:三菱plc模拟量编程 编辑:程序博客网 时间:2024/05/22 13:48

题目链接: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. * */public class BestTimetoBuyAndSellStock {//198 / 198 test cases passed.//Status: Accepted//Runtime: 251 ms//Submitted: 0 minutes ago    public int maxProfit(int[] prices) {        if(prices.length <= 1) return 0;    int maxProfit = 0;//最大利润    int minPrice = prices[0]; //当前最低价格    for (int i = 1; i < prices.length; i++) {maxProfit = Math.max(maxProfit, prices[i] - minPrice);minPrice = Math.min(minPrice, prices[i]);}    return maxProfit;    }public static void main(String[] args) {// TODO Auto-generated method stub}}


0 0
原创粉丝点击