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;   
        }
    }
    

      

  • 相关阅读:
    MR架构
    概念词汇
    数仓项目06:DWD层
    Informatic学习总结_day03
    oracle_创建和管理表
    oracle_使用子查询创建表
    oracle数据类型
    文本变语音引擎 ekho
    [LNOI2014]LCA
    POJ 2942 Knights of the Round Table
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3771631.html
Copyright © 2011-2022 走看看