Enterprise Resource Planning Blogs by Members
Gain new perspectives and knowledge about enterprise resource planning in blog posts from community members. Share your own comments and ERP insights today!
cancel
Showing results for 
Search instead for 
Did you mean: 
kallolathome
Active Participant
1,852

Introduction


This is part of the Easy way to write algorithms in ABAP: Series 01. For more algorithms, please check the main blog-post.

Problem


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 choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

 

Example 1:
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.

Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105

  • 0 <= prices[i] <= 104


Solution


Time Complexity: O(n)

Space Complexity: O(1)

ABAP


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.

JavaScript


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;

};

Python


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

 

N.B: For ABAP, I am using SAP BTP ABAP Environment 2211 Release.

Happy Coding! 🙂
1 Comment
Labels in this area