Say you have an array for which theithelement is the price of a given stock on dayi. 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. 大意是:有一个数组,数组的下标表示第几...
代码: 1publicintmaxProfit(int[] prices) {2intlen =prices.length ;3if(len < 2)return0;45intmin = prices[0] ;6intmaxProfit = 0;78for(inti = 1 ; i < len ; i++){9inttemp = prices[i] - min;//当前值减去前i-1个值的最小值10if(maxProfit < temp) maxProfit = temp;//更新最大...
LeetCode121. Best Time to Buy and Sell Stock JonesM https://leetcode.com/problems/best-time-to-buy-and-sell-stock/leetcode.com/problems/best-time-to-buy-and-sell-stock/ 解题思路 1. 暴力 O(n2) 复杂度,超时 class Solution { public: int maxProfit(vector<int>& prices) { int maxVal...
classSolution:defmaxProfit(self,prices:List[int])->int:## 双指针解法left,right=0,1# left=buy, right=sellmaxP=0whileright<len(prices):## 遍历整个 listifprices[right]>prices[left]:## 在存在赚钱机会的条件下profit=prices[right]-prices[left]maxP=max(maxP,profit)else:## 对于任意一个右指...
英文网址:121. Best Time to Buy and Sell Stock。 中文网址:121. 买卖股票的最佳时机。 思路分析 求解关键:在最多只允许交易一次的情况下,要求出一段时间内的最大利润,我们只需找到股价最低的一天买进,然后在股价最高的一天卖出即可(并且要满足先买后卖的规则)。因此我们可以在遍历的时候记录之前遍历的最小...
输入:prices = [7,6,4,3,1]输出:0解释:在这种情况下, 没有交易完成, 所以最大利润为 0。 提示: 1 <= prices.length <= 105 0 <= prices[i] <= 104 题目难度:简单 通过次数:1.6M 提交次数:2.8M 贡献者:LeetCode 相关标签 数组动态规划 ...
Leetcode 121.122.123 买卖股票得最佳时机系列 best-time-to-buy-and-sell-stock系列——先买入后卖出股票的最大值 tag 数组,1、Sayyouhaveanarrayforwhichthe i th elementisthepriceofagivenstockondayi .Ifyouwereonlypermittedtocompleteatmostonetransa
原题地址 https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 题意 给定数组...
LeetCode.jpg 121. 买卖股票的最佳时机 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例1:
121. Best Time to Buy and Sell Stock You are given an arraypriceswhereprices[i]is the price of a given stock on theithday. You want to maximize your profit by choosing asingle dayto buy one stock and choosing adifferent day in the futureto sell that stock....