Skip to content

Instantly share code, notes, and snippets.

@daifu
Last active December 14, 2015 17:09
Show Gist options
  • Select an option

  • Save daifu/5120178 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5120178 to your computer and use it in GitHub Desktop.
Say you have an array for which the ith element is the price of a given stock on day i.
/*
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
*/
import java.util.*;
public class Solution {
public class Stock implements Comparable<Stock>{
public int index;
public int price;
public Stock(int i, int p) {
this.index = i;
this.price = p;
}
@Override
public int compareTo(Stock other) {
return Integer.valueOf(other.price).compareTo(price);
}
}
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
int size = prices.length;
int diff = 0;
int max_diff = 0;
PriorityQueue<Stock> queue = new PriorityQueue<Stock>();
for(int i = 0; i < size; i++) {
queue.offer(new Stock(i, prices[i]));
}
Stock max_price = queue.poll();
for(int i = 0; i < size; i++) {
while(max_price.index < i) {
max_price = queue.poll();
}
diff = max_price.price - prices[i];
if(diff > max_diff) {
max_diff = diff;
}
}
return max_diff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment