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.

    原题链接:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

    题目:如果你有一个数组,当中的第 i 个元素代表给定的第 i 天的股票价格。

    假设你被同意至多完毕一个交易(如,买一和卖一股票)。设计一个算法找出最大的利润。

    最Naive的解法,就是遍历全部的  后 - 前 ,找出最小值。超时了。

    	public static int maxProfit(int[] prices){
    		int len = prices.length;
    		if(len <= 1)
    			return 0;
    		int max = 0;
    		for(int i=0;i<len;i++){
    			for(int j=i+1;j<len;j++){
    				int profit = prices[j] - prices[i];
    				if(max < profit)
    					max = profit;
    			}
    		}
    		return max;
    	}

    以下的方法就简便多了,首先赋首元素的值给最小,依次向后计算利润,每次与最大值比較并保存新的最大值和新的最小值。

    	public static int maxProfit(int[] prices){
    		int len = prices.length;
    		if(len <= 1)
    			return 0;
    		int min = prices[0],max = 0;
    		for(int i=1;i<len;i++){
    			int profit = prices[i] - min;
    			if(max < profit)
    				max = profit;
    			if(min > prices[i])
    				min = prices[i];
    		}
    		return max;
    	} 


  • 相关阅读:
    Python matplotlib基本设置
    Python可视化工具
    使用Python进行数据分析——常见实用的第三方库
    Python第三方库安装
    Python pip的安装
    Python cx_Oracle数据库连接
    Python安装使用(WinXP)
    大数据学习路线(转载)
    SQL 数据库学习之路-转自大神笔记
    Java字符串处理函数汇总
  • 原文地址:https://www.cnblogs.com/yfceshi/p/6900691.html
Copyright © 2011-2022 走看看