package org.wesome.dsalgo;
public class StockBuySell {
public static void maxProfit(int[] sharePrice) {
if (sharePrice == null || sharePrice.length == 0) {
System.out.println("invalid share Price = " + sharePrice);
return;
}
int buyPrice = sharePrice[0];
int sellPrice = sharePrice[0];
int buyDay = 0;
int sellDay = 0;
int profit = Integer.MIN_VALUE;
for (int i = 0; i < sharePrice.length; i++) {
int todayPriceDiff = sharePrice[i] - buyPrice;
if (todayPriceDiff > profit) {
profit = todayPriceDiff;
sellDay = i + 1;
sellPrice = sharePrice[i];
}
if (sharePrice[i] < buyPrice) {
buyPrice = sharePrice[i];
buyDay = i + 1;
}
}
System.out.println("buyPrice at = " + buyPrice + "Rs on = " + buyDay + " day and sellPrice at = " + sellPrice + " Rs on = " + sellDay + "day will give max profit of = " + profit);
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Test;
public class StockBuySellTest {
@Test
void maxProfit() {
StockBuySell.maxProfit(new int[]{100, 180, 260, 310, 40, 535, 695});
}
}
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}