您的位置:首页 > 编程语言 > Java开发

best-time-to-buy-and-sell-stock Java code

2017-10-24 13:15 281 查看
Say you have an array for which the i th 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 int maxProfit(int[] prices) {
if(prices.length<2){
return 0;
}
int maxProfit=0;
int temp = prices[0];
for(int i=1; i<prices.length; i++){
temp = Math.min(temp, prices[i]);
maxProfit = Math.max(maxProfit, prices[i]-temp);
}
return maxProfit;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java stock