prices
where prices[i]
is the price of a given stock on the ith
day.0
.Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy
before you sell.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
1 <= prices.length <= 105
0 <= prices[i] <= 104
CLASS zcl_stock DEFINITION
PUBLIC
FINAL
CREATE PUBLIC .
PUBLIC SECTION.
* Mandatory declaration
INTERFACES if_oo_adt_classrun.
PROTECTED SECTION.
PRIVATE SECTION.
TYPES ty_prices TYPE STANDARD TABLE OF i WITH DEFAULT KEY.
METHODS StockBuySell
IMPORTING lt_prices TYPE ty_prices
RETURNING VALUE(rv_max_profit) TYPE i.
ENDCLASS.
CLASS zcl_stock IMPLEMENTATION.
METHOD if_oo_adt_classrun~main.
out->write( |{ StockBuySell( VALUE #( ( 7 ) ( 1 ) ( 5 ) ( 3 ) ( 6 ) ( 4 ) ) ) }| ).
ENDMETHOD.
METHOD StockBuySell.
DATA(lv_min_price) = lt_prices[ 1 ].
LOOP AT lt_prices ASSIGNING FIELD-SYMBOL(<lfs_wa>).
lv_min_price = nmin( val1 = lv_min_price
val2 = <lfs_wa> ).
rv_max_profit = nmax( val1 = rv_max_profit
val2 = ( <lfs_wa> - lv_min_price ) ).
ENDLOOP.
UNASSIGN <lfs_wa>.
FREE lv_min_price.
ENDMETHOD.
ENDCLASS.
var maxProfit = function(prices) {
var lv_min_price = prices[0],
lv_max_profit = 0;
for(let i = 0; i < prices.length; i++){
lv_min_price = Math.min(lv_min_price, prices[i]);
lv_max_profit = Math.max(lv_max_profit, (prices[i] - lv_min_price));
}
return lv_max_profit;
};
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lv_min_price = prices[0]
lv_max_profit = 0
for i in range(0, len(prices)):
lv_min_price = min(lv_min_price, prices[i])
lv_max_profit = max(lv_max_profit, (prices[i] - lv_min_price))
return lv_max_profit
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
5 | |
4 | |
3 | |
2 | |
2 | |
2 | |
2 | |
2 | |
2 | |
1 |