Leetcode之121. 买卖股票的最佳时机
2019-08-12 16:46
120 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_43826123/article/details/99311448
题目:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格
来源:力扣(LeetCode)
题解:
第一层遍历从头开始(i),第二层遍历从当前位置的下一个开始(j),找到prices[j]-prices[i]的最大值
class Solution { public int maxProfit(int[] prices) { int price,max=0; for(int i=0;i<prices.length;i++) for(int j=i+1;j<prices.length;j++) { price=prices[j]-prices[i]; max=max>price?max:price;//找到最大值 } return max; } }
相关文章推荐
- LeetCode刷题笔记121:买卖股票的最佳时机
- Leetcode121: 买卖股票的最佳时机
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode 121 买卖股票的最佳时机 Python
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- LeetCode || 121-124. 买卖股票的最佳时机
- C++Leetcode121:买卖股票的最佳时机
- leetcode-121-买卖股票的最佳时机
- 基础算法之买卖股票最佳时机(Leetcode-121)
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- LeetCode 买卖股票的最佳时机(C++)
- [LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
- 基础算法之买卖股票的最佳时机 II(Leetcode-122)
- [Java语言] [Leetcode] Best Time to Buy and Sell Stock 买卖股票的最佳时机
- LeetCode 121. 买卖股票的最佳时机
- Leetcode 买卖股票的最佳时机 II
- leetcode 买卖股票的最佳时机
- Leetcode122:买卖股票的最佳时机 II
- LeetCode——121. 买卖股票的最佳时机