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. [Thought] Using greedy algorithm to solve this problem . Scan from left to right , and keep track the minimum price . If the ...
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:## 对于任意一个右指...
Best Time to Buy and Sell Stock Say you have an array for which theith element is the price of a given stock on dayi. Design an algorithm to find the maximum profit. You may complete at mosttwotransactions. Note: You may not engage in multiple transactions at the same time (i.e., ...
在计算第一个时,因为sell之前没有buy因此只能从第一个元素开始,buy的第一个设置为-prices[0],sell和presell设置为0,这样就可以计算第一个元素的buy。 另外还有一道比较类似的robber题目:https://leetcode.com/problems/house-robber/?tab=Description。思路还是应用一个序列,只不过stock里面要考虑以...
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 因为可以进行无限次交易,并且在下一次buy之前必须已经sell。所以只需要把所有price曲线价格上涨的部分加起来就行。 class Solution(object): def maxProfit(self, prices): """
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 = 0; int n = prices.size(); for(int i = 0; ...
Can you solve this real interview question? Best Time to Buy and Sell Stock - You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choo
Description Description Editorial Editorial Solutions Submissions Submissions Code Testcase Test Result Test Result All Solutions Ln 1, Col 1 Case 1Case 2 prices = [7,1,5,3,6,4] 1 2 [7,1,5,3,6,4] [7,6,4,3,1] Source
My code: publicclassSolution{publicintmaxProfit(int[]prices){if(prices==null||prices.length<2)return0;boolean isInMode=false;inti=0;intmax=0;inttempMax=0;while(i<prices.length){for(intj=i+1;j<prices.length;j++){if(prices[j]<=prices[i]&&!isInMode){i=j;tempMax+=max;max=0;if(i...
Best Time to Buy and Sell Stock II class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ return sum(max(prices[i+1]-prices[i],0) for i in range(len(prices)-1)) 解题思路:只要第二天的价格比前一天高,就买了再卖...