基于java計算買賣股票的最佳時機
這篇文章主要介紹了基于java計算買賣股票的最佳時機,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下
問題:
可以將問題轉(zhuǎn)化為如下圖所示,即求多個累計的收入差
分析:
如果當前位置i的價格比i+1的價格高,則當前不是買入點,則繼續(xù)判斷下一個位置,
如果當前位置i的價格比i+1的價格低,并且i+1仍比i+1+1低,則在當前位置買入,知道i+n比i+n+1大時,賣出。
繼續(xù)下一輪判斷
package com.example.demo; public class Test121 { /** * 多個 * * @param prices * @return */ public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int cur = 0; int vally = prices[0]; int peak = 0; int income = 0; while (cur < prices.length - 1) { //找到賣出點,谷底 while (cur < prices.length - 1 && prices[cur] >= prices[cur + 1]) { cur++; } vally = prices[cur]; //找到比當前大的值(即最高點,頂峰) while (cur < prices.length - 1 && prices[cur] <= prices[cur + 1]) { cur++; } peak = prices[cur]; income += peak - vally; //如果此時cur仍然沒有到最后,則進行再一次循環(huán) } return income; } public static void main(String[] args) { Test121 t = new Test121(); int[] arr = {7, 1, 5, 3, 6, 4}; int i = t.maxProfit(arr); System.out.println(i); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringMVC請求、響應(yīng)和攔截器的使用實例詳解
攔截器(Interceptor) 它是一個Spring組件,并由Spring容器管理,并不依賴Tomcat等容器,是可以單獨使用的,這篇文章給大家介紹SpringMVC請求、響應(yīng)和攔截器的使用,感興趣的朋友一起看看吧2024-03-03SpringCloud Gateway HttpWebHandlerAdapter鏈路調(diào)用請求流程介
Spring Cloud Gateway旨在為微服務(wù)架構(gòu)提供一種簡單有效的、統(tǒng)一的 API 路由管理方式。Spring Cloud Gateway 作為 Spring Cloud 生態(tài)系中的網(wǎng)關(guān),它不僅提供統(tǒng)一的路由方式,并且基于 Filter 鏈的方式提供了網(wǎng)關(guān)基本的功能,例如:安全、監(jiān)控/埋點和限流等2022-10-10