Created
July 19, 2020 15:49
-
-
Save bangarharshit/ba3e827f03bb59cf0b583842a14fb2ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
// Uber $ - 5 3 4 6 7 8 9 9 7 6 5 8 | |
// Any day - You can buy 1 stock or you can sell all your stocks or do nothing. | |
// You have to maximize your profit. | |
// (9-5) + (9-3) + (9-4) + (9-6) + (9-7) + (8-7) + (8-6) + (8-5) | |
// 8, 5, 6, 7, 9, 9, 8 | |
// max = 9 | |
public class StockBuySell { | |
public static int maxProfit(List<Integer> list) { | |
int max = list.get(list.size()-1); | |
int totalProfit = 0; | |
for (int i=list.size()-2; i>=0; i--) { | |
if (max < list.get(i)) { | |
max = list.get(i); | |
} else { | |
totalProfit = totalProfit + (max - list.get(i)); | |
} | |
} | |
return totalProfit; | |
} | |
public static void main(String[] args) { | |
System.out.println(StockBuySell.maxProfit(Arrays.asList(5, 3, 4, 6, 7, 8, 9, 9, 7, 6, 5, 8))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment