zoukankan      html  css  js  c++  java
  • leetcode--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 Solution {
        /**This is a fundamental problem.<br>
         * The running time is O(n).<br>
         * It can be solved by divide-conquer method too with O(nln n)time
         * @author Averill Zheng
         * @version 2014-06-04
         * @since JDK 1.7
         */ 
        public int maxProfit(int[] prices) {
            int profit = 0;
            int length = prices.length;
            int buyDate = 0, sellDate = 0, tempProfit = 0;
            for(int i = 1; i < length; ++i){
            	if(prices[i] >= prices[sellDate]){
            		tempProfit = prices[i] - prices[buyDate];
            		sellDate = i;
            		profit = (profit < tempProfit) ? tempProfit : profit; 
            	}
            	if(prices[i] < prices[buyDate]){
            		buyDate = sellDate = i;
            		tempProfit = 0;
            	}
            }
            return profit;   
        }
    }
    

      

  • 相关阅读:
    Super Jumping! Jumping! Jumping!(求最大上升子序列和)
    HZNU1837——一道简单的方程
    C
    B
    A
    bfs-Find a way
    bfs——Red and Black
    dfs——n皇后问题
    dfs——n皇后问题
    python画图中colorbar设置刻度和标签字体大小
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3771631.html
Copyright © 2011-2022 走看看