【LeetCode从零单排】No121 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 stoc

题目

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.

又是时间复杂度,离真相就差一行代码。。。还是没想出来,看了discuss才知道答案。


代码

public class Solution {
    public int maxProfit(int[] prices) {

        if (prices.length<=0 || prices.length==1) return 0;
    	   int maxProfit=0;
    	   int minTemp=prices[0];
    	   for(int i=1;i<prices.length;i++){
    		   if(prices[i]<minTemp){
    			   minTemp=prices[i];    			 
    		   }
    		   else{
    			   if(prices[i]-minTemp>maxProfit){
    				   maxProfit=prices[i]-minTemp;
    			   }
    		   }
    	   }
    	   return maxProfit;   	
    }
}




/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


目录
相关文章
|
算法
LeetCode 309. Best Time to B & S Stock with CD
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票)
68 0
LeetCode 309. Best Time to B & S Stock with CD
|
算法
LeetCode 188. Best Time to Buy and Sell Stock IV
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
72 0
LeetCode 188. Best Time to Buy and Sell Stock IV
|
算法
LeetCode 123. Best Time to Buy and Sell Stock III
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
89 0
LeetCode 123. Best Time to Buy and Sell Stock III
|
算法
LeetCode 121. Best Time to Buy and Sell Stock
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果您最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
68 0
LeetCode 121. Best Time to Buy and Sell Stock
Leetcode-Easy 121. Best Time to Buy and Sell Stock
Leetcode-Easy 121. Best Time to Buy and Sell Stock
117 0
Leetcode-Easy 121. Best Time to Buy and Sell Stock
|
算法
LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50814399 翻译 话说你有一个数组,其中第i个元素表示在第i天的股票价格。
855 0
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
38 6
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 26. 树的子结构
这篇文章提供了解决LeetCode上"剑指Offer 26. 树的子结构"问题的Python代码实现和解析,判断一棵树B是否是另一棵树A的子结构。
34 4
|
1月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
65 2
|
1月前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
33 7