Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package com.leetcode.arrays; | ||
|
||
/** | ||
* Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ | ||
* | ||
* @author rampatra | ||
* @since 2019-04-23 | ||
*/ | ||
public class BuySellStocks { | ||
|
||
/** | ||
* Time complexity: O(n) | ||
* where, | ||
* n = no. of stock prices | ||
* <p> | ||
* Runtime: <a href="https://leetcode.com/submissions/detail/224463627/">0 ms</a>. | ||
* | ||
* @param prices | ||
* @return | ||
*/ | ||
public static int maxProfit(int[] prices) { | ||
int profit = 0; | ||
int buyPrice = Integer.MAX_VALUE; | ||
|
||
for (int i = 0; i < prices.length; i++) { | ||
if (prices[i] < buyPrice) { | ||
buyPrice = prices[i]; | ||
} else if (prices[i] - buyPrice > profit) { | ||
profit = prices[i] - buyPrice; | ||
} | ||
} | ||
|
||
return profit; | ||
} | ||
|
||
public static void main(String[] args) { | ||
|
||
System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4})); | ||
System.out.println(maxProfit(new int[]{7, 1, 5, 0, 6, 4})); | ||
System.out.println(maxProfit(new int[]{4, 3, 2, 1})); | ||
|
||
// edge cases | ||
System.out.println(maxProfit(new int[]{})); | ||
System.out.println(maxProfit(new int[]{1})); | ||
} | ||
} |