《漫画算法2》源码整理-9 股票交易最大收益
生活随笔
收集整理的這篇文章主要介紹了
《漫画算法2》源码整理-9 股票交易最大收益
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
股票交易最大收益
public class StockProfit {public static int maxProfitFor1Time(int prices[]) {if(prices==null || prices.length==0) {return 0;}int minPrice = prices[0];int maxProfit = 0;for (int i = 1; i < prices.length; i++) {int profit = prices[i] - minPrice;if(profit > maxProfit){maxProfit = profit;} else if (prices[i] < minPrice) {minPrice = prices[i];}}return maxProfit;}public static int maxProfitForAnyTime(int[] prices) {int maxProfit = 0;for (int i = 1; i < prices.length; i++) {if (prices[i] > prices[i-1])maxProfit += prices[i] - prices[i-1];}return maxProfit;}//最大買賣次數(shù)private static int MAX_DEAL_TIMES = 2;public static int maxProfitFor2Time(int[] prices) {if(prices==null || prices.length==0) {return 0;}//表格的最大行數(shù)int n = prices.length;//表格的最大列數(shù)int m = MAX_DEAL_TIMES*2+1;//使用二維數(shù)組記錄數(shù)據(jù)int[][] resultTable = new int[n][m];//填充初始狀態(tài)resultTable[0][1] = -prices[0];resultTable[0][3] = -prices[0];//自底向上,填充數(shù)據(jù)for(int i=1;i<n;++i) {for(int j=1;j<m;j++){if((j&1) == 1){//j為奇數(shù)的情況resultTable[i][j] = Math.max(resultTable[i-1][j], resultTable[i-1][j-1]-prices[i]);}else {//j為偶數(shù)的情況resultTable[i][j] = Math.max(resultTable[i-1][j], resultTable[i-1][j-1]+prices[i]);}}}//返回最終結(jié)果return resultTable[n-1][m-1];}public static int maxProfitFor2TimeV2(int[] prices) {if(prices==null || prices.length==0) {return 0;}//表格的最大行數(shù)int n = prices.length;//表格的最大列數(shù)int m = MAX_DEAL_TIMES*2+1;//使用一維數(shù)組記錄數(shù)據(jù)int[] resultTable = new int[m];//填充初始狀態(tài)resultTable[1] = -prices[0];resultTable[3] = -prices[0];//自底向上,填充數(shù)據(jù)for(int i=1;i<n;i++) {for(int j=1;j<m;j++){if((j&1) == 1){//j為奇數(shù)的情況resultTable[j] = Math.max(resultTable[j], resultTable[j-1]-prices[i]);}else {//j為偶數(shù)的情況resultTable[j] = Math.max(resultTable[j], resultTable[j-1]+prices[i]);}}}//返回最終結(jié)果return resultTable[m-1];}public static int maxProfitForKTime(int[] prices, int k) {if(prices==null || prices.length==0 || k<=0) {return 0;}//表格的最大行數(shù)int n = prices.length;//表格的最大列數(shù)int m = k*2+1;//使用一維數(shù)組記錄數(shù)據(jù)int[] resultTable = new int[m];//填充初始狀態(tài)for(int i=1;i<m;i+=2) {resultTable[i] = -prices[0];}//自底向上,填充數(shù)據(jù)for(int i=1;i<n;i++) {for(int j=1;j<m;j++){if((j&1) == 1){//j為奇數(shù)的情況resultTable[j] = Math.max(resultTable[j], resultTable[j-1]-prices[i]);}else {//j為偶數(shù)的情況resultTable[j] = Math.max(resultTable[j], resultTable[j-1]+prices[i]);}}}//返回最終結(jié)果return resultTable[m-1];}public static void main(String[] args) {int[] prices = {9,2,7,4,3,1,8,4};System.out.println(maxProfitFor1Time(prices));System.out.println(maxProfitForAnyTime(prices));System.out.println(maxProfitFor2Time(prices));System.out.println(maxProfitForKTime(prices, 3));}}總結(jié)
以上是生活随笔為你收集整理的《漫画算法2》源码整理-9 股票交易最大收益的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《漫画算法2》源码整理-8 链表中倒数第
- 下一篇: 两种金钱观