DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

3 2

Buy and Sell Stocks-I and II

Problem link : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/
Twitter | LinkedIn

This is basic array question helps you to understand arrays better

part -1: buying and selling is allowed once

in this we will assume maximum profit zero initially and buying price maximum. We will iterate the array of prices, if we find the minimum buyprice less than the previous buying price we will update the buy price, for this we will use if statement if(prices[i]<buyprice>){ buyprice =price(i);} this loop will execute only if price[i] value is smaller than the buyprice, or we can use the java Math.min class of java.

Similarly, we update the maxProfit if our maxProfit is more than price[i]-buyPrice or previous maxProfit. for this either we can use else if statement or MaxProfit= Math.max(MaxProfit, prices[i]-buyPrice);

class Solution {
    public int maxProfit(int[] prices) {
        int MaxProfit=0;
        int buyPrice= Integer.MAX_VALUE;

        for(int i=0; i< prices.length; i++){
            if(prices[i]<buyPrice){
                buyPrice= prices[i];
            }
         // else if(MaxProfit<prices[i]- buyPrice){
         //    MaxProfit= prices[i]-buyPrice;
            //}
            MaxProfit= Math.max(MaxProfit, prices[i]-buyPrice);


    }
        return MaxProfit;
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay