zoukankan      html  css  js  c++  java
  • 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.

    Example 1:

    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
    

    Example 2:

    Input: [7, 6, 4, 3, 1]
    Output: 0
    
    In this case, no transaction is done, i.e. max profit = 0.
    

     此题属于动态规划问题,动态规划的特点原问题可以被分解为若干规模较小的子问题,注意状态方程,当遍历到数组的某一值时,如果该值比之前最小元素还小,则将其保存为最小元素,否则,差值就是到该数组值的时候,最大的利润。代码如下:

    public class Solution {

        public int maxProfit(int[] prices) {

            int max = 0;

            if(prices.length==0) return max;

            int start = prices[0];

            for(int i=1;i<prices.length;i++){

                if(prices[i]<start){

                    start = prices[i];

                }else{

                    max = Math.max(max,prices[i]-start);

                }

            }

            return max;

        }

    }

     
  • 相关阅读:
    闭包(closure)与协程共用时要注意的事情
    mysql---视图
    职责链模式
    JavaScript DOM(一)
    9.7 迭代
    [BLE--Link Layer]设备蓝牙地址
    Loopback測试软件AX1用户手冊 V3.1
    操作系统
    OpenCV特征点检測------Surf(特征点篇)
    linux 命令 xxd
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358615.html
Copyright © 2011-2022 走看看