We need to find out the maximum difference (which will be the maximum profit) between two numbers in the given array. Also, the second number (selling price) must be larger than the first one (buying price).
Click here to see the full article post
We need to find out the maximum difference (which will be the maximum profit) between two numbers in the given array. Also, the second number (selling price) must be larger than the first one (buying price).
Click here to see the full article post
int maxProfit(int* prices, int pricesSize) {
if (NULL == prices || pricesSize <= 0)
return 0;
int minPrice = prices[0];
int max_profit = 0, i = 0;
for(i = 1; i < pricesSize; i ++)
{
int tmpProfit = prices[i] - minPrice;
if (prices[i] < minPrice)
{
minPrice = prices[i];
}
if ((max_profit < tmpProfit))
{
max_profit = tmpProfit;
}
}
return max_profit;
}
class Solution(object):
def maxProfit(self, prices):
sol = list()
for index, value in enumerate(prices):
starting=prices[:index+1]
ending=prices[index+1:]
if starting and ending:
value = max(ending)-min(starting)
sol.append(value)
if sol:
j=max(sol)
if j>0:
return (max(sol))
else:
return 0
else:
return 0