121-Best Time to Buy and Sell Stock
生活随笔
收集整理的這篇文章主要介紹了
121-Best Time to Buy and Sell Stock
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:
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.目標(biāo)是求數(shù)組中的某兩個(gè)值的差(最大差值),前提是大的數(shù)在小的數(shù)后面
2.循環(huán)遍歷數(shù)組,設(shè)置一個(gè)當(dāng)前最小值min(初始為Integer.MAX_VALUE)和一個(gè)最大差值max(初始化為0)
? ?每次更新min,并更新max(當(dāng)前元素值-min)
public class Solution {public int maxProfit(int[] prices) {int len=prices.length; //數(shù)組長(zhǎng)度int max=0; //最大差值int min=Integer.MAX_VALUE; //當(dāng)前最小值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;}
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/hwu2014/p/4422009.html
總結(jié)
以上是生活随笔為你收集整理的121-Best Time to Buy and Sell Stock的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 做一个门套?多少钱
- 下一篇: 求一个关于海绵宝宝的qq网名