• 121. 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.

    链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock/

    一刷,存min和profit

    class Solution(object):
        def maxProfit(self, prices):
            if not prices:
                return 0
            lowest = prices[0]
            profit = 0
            for idx in range(len(prices)):
                if prices[idx] < lowest:
                    lowest = prices[idx]
                elif prices[idx] - lowest > profit:
                    profit = prices[idx] - lowest
            return profit

    2/18/2017, Java

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices.length <= 1) return 0;
     4         int min = prices[0];
     5         int maxDiff = 0;
     6         
     7         for(int i = 1; i < prices.length; i++) {
     8             if (prices[i] < min ) min = prices[i];
     9             else if (prices[i] - min > maxDiff ) maxDiff = prices[i] - min;
    10         }
    11         return maxDiff;
    12     }
    13 }

    4/16/2017

    BB电面准备

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices.length <= 0) return 0;
     4         int min = prices[0];
     5         int maxProfit = 0;
     6         
     7         for (int i = 1; i < prices.length; i++) {
     8             if (prices[i] < min) {
     9                 min = prices[i];
    10             } else if (prices[i] > prices[i - 1] && prices[i] - min > maxProfit) {
    11                 maxProfit = prices[i] - min;
    12             }
    13         }
    14         return maxProfit;
    15     }
    16 }
  • 相关阅读:
    使用PDO连接数据库
    ES6 promise
    弹框小三角
    封装弹窗功能
    css3 省略号
    使mac支持NTFS读写问题
    Vue 打包 build 前需要修改哪些配置和路径
    eslint配置大全
    在elementUI中使用 el-autocomplete 实现远程搜索的下拉框
    element-UI table自定义表头
  • 原文地址:https://www.cnblogs.com/panini/p/5613259.html
Copyright © 2020-2023  润新知