Best Time to Buy and Sell Stock
to and Time Best Buy Stock Sell
2023-09-14 09:08:11 时间
题目
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.
方法
和同一时候找一个数组中的最大值和最小值类似。
加了限制条件:最小值仅仅能在最大值的前面。
1. 先初始化最小值和最大值为数组的第一个元素,maxProfit = 0;
2.遍历一遍数组:假设元素大于最大值,则更新最大值和maxProfit
假设元素小于最小值,同一时候更新最大值和最小值。
public int maxProfit(int[] prices) { if (prices == null) { return 0; } int len = prices.length; if (len == 0 || len == 1) { return 0; } int maxPro = 0; int min = prices[0]; int max = prices[0]; for (int i = 1; i < len; i++) { if (prices[i] > max) { max = prices[i]; int tempMaxPro = max - min; if (tempMaxPro > maxPro) { maxPro = tempMaxPro; } } else if (prices[i] < min) { min = prices[i]; max = prices[i]; } } return maxPro; }
相关文章
- 【DataGuarad】ORA-1153 trying to turn on Flashback for Physical Standby Database 2011-10-
- Best Time to Buy and Sell Stock1,2,3,4
- [CSS] Using single grid-template-area and justify-self to select arrow down icon in select
- [CSS3] Use media query to split css files and Dark mode (prefers-color-scheme: dark)
- [Javascript] Construct a Regex to Match Twitter Mentions with Regexr
- [JUnit] Introduce to Junit and it annotations
- [TypeScript] Configuring TypeScript Which Files to Compile with "Files" and "OutDir"
- [Falcor] Indroduce to Model
- 领扣-121/122/123/188 最佳买卖时机 Best Time to Buy and Sell MD
- [Typescript] Using 'Pick' to create a sub-type from original type
- [PWA] Add Push Notifications to a PWA with React in Chrome and on Android
- [Tools] Convert SVG to a PDF in Node with PDFKit and SVG.js
- [Tailwind] Abstract Utility Classes to BEM Components in Tailwind
- [Nuxt] Use Vuex Actions to Delete Data from APIs in Nuxt and Vue.js
- [React Fundamentals] Using Refs to Access Components
- difference between SAP UI5 RTL false and true - set breakpoint to change behavior
- Step by step to create web service in Cloud Application studio and bind it to a custom action in sta
- bs4 FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
- How to improve Java's I/O performance( 提升 java i/o 性能)
- LeetCode 121 Best Time to Buy and Sell Stock
- Unable to update the EntitySet 'T_JsAPI' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
- Best Time to Buy and Sell Stock III
- leetcode 121. Best Time to Buy and Sell Stock
- leetcode 122. Best Time to Buy and Sell Stock II