121-Best Time to Buy and Sell Stock
生活随笔
收集整理的這篇文章主要介紹了
121-Best Time to Buy and Sell Stock
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
思路:
1.目標是求數組中的某兩個值的差(最大差值),前提是大的數在小的數后面
2.循環遍歷數組,設置一個當前最小值min(初始為Integer.MAX_VALUE)和一個最大差值max(初始化為0)
? ?每次更新min,并更新max(當前元素值-min)
public class Solution {public int maxProfit(int[] prices) {int len=prices.length; //數組長度int max=0; //最大差值int min=Integer.MAX_VALUE; //當前最小值for(int i=0;i<len;i++) {if(prices[i]<min)min=prices[i];if(prices[i]-min>max)max=prices[i]-min;}return max;}
}
?
轉載于:https://www.cnblogs.com/hwu2014/p/4422009.html
總結
以上是生活随笔為你收集整理的121-Best Time to Buy and Sell Stock的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做一个门套?多少钱
- 下一篇: ios 8+ (xcode 6.0 +)