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.

最简单的方法就是穷举,O(n2)。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int max = 0;
 6         for(int i = 0; i < prices.length; i ++){
 7             for(int j = i + 1; j <  prices.length; j ++){
 8                 int cur = prices[j] - prices[i];
 9                 if(cur > max) max = cur;
10             }
11         }
12         return max;
13     }
14 }

这题有O(n)算法。 使用额外的prices.length空间。 存入从后往前n个数里最大的数。 这样就不用双层循环了。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int max = 0;
 6         int maxnum[] = new int[prices.length];
 7         if(prices.length == 0) return 0;
 8         if(prices.length == 1) return 0;
 9         maxnum[prices.length - 1] = prices[prices.length - 1];
10         for(int i = prices.length - 2; i > -1; i --){
11             if(prices[i] > maxnum[i + 1]) maxnum[i] = prices[i];
12             else maxnum[i] = maxnum[i + 1];
13         }
14         for(int i = 0; i < prices.length-1; i ++){
15             if(maxnum[i+1] - prices[i] > max)max =  maxnum[i+1] - prices[i]; 
16         }
17         return max;
18     }
19 }

 第二遍:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         int max = 0;
 6         if(prices.length == 0)return 0;
 7         int highest = 0;
 8         for(int i = prices.length - 1; i > 0; i --){
 9             highest = Math.max(prices[i],highest);
10             int cur = highest - prices[i - 1];
11             if(cur > max) max = cur;
12         }
13         return max;
14     }
15 }

 

posted on 2013-09-11 05:16  Step-BY-Step  阅读(195)  评论(0编辑  收藏  举报

导航