MaxProfit in Python and C++ Codility Solutions Lesson 9

preview_player
Показать описание
This is the Codility solution of Lesson 9 exercise MaxProfit, it is presented and written in C++ and in Python. Good array exercise, for coding interviews and for algorithmic skills development.
Hope you Enjoy it !

🍓 If you want to follow structured courses with more details and practice exercises check my "About" page for Discount Coupons on my Udemy courses covering: Python basics, Object Oriented Programming and Data Analysis with NumPy and Pandas, ... more courses are on the way drop me a message if you have a particular interesting topic! Good luck!

#python #cplusplusprogramming #codinginterview
Рекомендации по теме
Комментарии
Автор

Great explanation!
You could also do s = max(s, A[i]-mymin). That way, if you find a lower minimum, you set mymin to that and then compare new differences with s (where s is the current maximum provided from the previous minimum).

def solution(A):
n = len(A)
if n==0 or n==1:
return 0
mymin = A[0]
s = 0
for i in range(n):
if mymin < A[i]:
s = max(s, A[i]-mymin)
elif mymin > A[i]:
mymin = A[i]
return s

ProfessorJT
Автор

Although my English is not good, but I like your videos very much, thank you for making this series.
This is my cod by Python, it also get 100%.
But it maybe not so rigorous, because I just studied for a month.


def solution(A):
if len(A) == 0:
return 0
min_num =
max_num = 0
for i in range(0, len(A)):
min_num = min(min_num, A[i])
if A[i] - min_num > 0:
max_num = max(max_num, A[i] - min_num)

return max_num

q
Автор

Lovely, thank you for making this series. I'm looking forward to the remaining questions.

tugaykapucu
Автор

My C# solution (100%)

public int solution(int[] A)
{
if (A.Length == 0) return 0;

int N = A.Length;

int minCost = A[0];
int maxProfit = 0;
int runningProfit = 0;
for (int i = 1; i < N; i++)
{
// if you find new buying position that is lesser
// then update the minCost and reset the runningProfit
if (A[i] < minCost)
{
minCost = A[i];
runningProfit = 0;
}
else
{
runningProfit += A[i] - A[i - 1];
}

maxProfit = Math.Max(runningProfit, maxProfit);
}

return maxProfit;
}

khadimali
join shbcf.ru